How to copy a file with Node.js?

Sometimes, we want to copy a file with Node.js.

In this article, we’ll look at how to copy a file with Node.js.

How to copy a file with Node.js?

To copy a file with Node.js, we can use the read stream’s pipe method.

For instance, we write:

const fs = require('fs')
const oldFile = fs.createReadStream('./foo.txt');
const newFile = fs.createWriteStream('./bar.txt');
oldFile.pipe(newFile);

to call fs.createReadStream with the path of the file to copy.

Then we call fs.createWriteStream with the path of the file to copy to.

Then we call oldFile.pipe with newFile to copy the contents of ./foo.txt to ./bar.txt.

Conclusion

To copy a file with Node.js, we can use the read stream’s pipe method.