How to copy a file in Node.js?
Last Updated :
06 Apr, 2023
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:
- file: Source filename path.
- option: It has to encode i.e. utf8.
- callback: The callback gets two arguments.
- filename: Filepath of the file to read.
- data: It is the data that we want to write.
- encoding: It is the encoding of the data.
- callback: It will show the error or null.
Implementation:
Javascript
const fs = require( 'fs' );
console.log( 'File Reading from file.txt ..........' );
fs.readFile( 'file.txt' , 'utf8' , readingFile);
function readingFile(error, data) {
if (error) {
console.log(error);
} else {
console.log(data);
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
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...