To copy the contents from one file to another file asynchronously, we can use the copyFile()
function from the fs
(filesystem) module in Node.js.
// Copy contents from one file
// to another file Asynchronously
fs.copyFile(src, dest, () => {
console.log("Copied Successfully!");
});
Let's say we have a file named myFile.txt
from which we need to copy the content (called source file) and another file called copyFile.txt
where we will have to write the copied contents (called destination file).
First, let's require the fs
module and define the source and destination files like this,
// require fs module
const fs = require("fs");
// source to copy content
const src = "myFile.txt";
// destination for copied content
const dest = "copyFile.txt";
To copy the file asynchronously we can use the fs.copyFile()
function and pass three arguments to the function:
src
as the first argumentdest
as the second argument- an error first callback function as the third argument that will get executed when contents are copied to the destination file.
It can be done like this,
// require fs module
const fs = require("fs");
// source to copy content
const src = "myFile.txt";
// destination for copied content
const dest = "copyFile.txt";
// use copyFile() function
// to copy contents from source file
// and write to destination file asynchronously
fs.copyFile(src, dest, (error) => {
// incase of any error
if (error) {
console.error(error);
return;
}
console.log("Copied Successfully!");
});
- The destination file will be created even if it doesn't exist in the system and the copied contents will be placed there.
- If the destination file is present then the contents inside the file are overwritten during the process.
See this example live in repl.it.