How to copy a file in Node.js?

Node.js is an open-source and cross-platform runtime environment for executing JavaScript code outside a browser. There are various platforms such as Windows, Linux, and Mac OS  where Node.js runs. 

There are various methods used in Node.js such as the readFile() and writeFile() methods. The readFile() and writeFile() method is used to copy the content of the file to another file.

Explanation:

  1. file: Source filename path.
  2. option: It has to encode i.e. utf8.
  3. callback: The callback gets two arguments.
  1. filename: Filepath of the file to read.
  2. data: It is the data that we want to write.
  3. encoding: It is the encoding of the data.
  4. callback: It will show the error or null.

Implementation: 

Javascript




const fs = require('fs'); // Import the filesystem module
 
console.log('File Reading from file.txt ..........');
 
// ReadFile method is used to read the content from file.txt
fs.readFile('file.txt', 'utf8', readingFile);
 
function readingFile(error, data) {
    if (error) {
        console.log(error);
    } else {
        console.log(data); // Printing the file.txt file's content
 
        // Creating new file - paste.txt with file.txt's content
        fs.writeFile('paste.txt', data, 'utf8', writeFile);
    }
}
 
function writeFile(error) {
    if (error) {
        console.log(error)
    } else {
        console.log('Content has been pasted to paste.txt file');
    }
}


Output:

Output