Categories
JavaScript Answers Nodejs

How to copy a file with Node.js?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *