Javascript – Fastest way to copy a file in Node.js

javascriptnode.js

The project that I am working on (Node.js) implies lots of operations with the file system (copying, reading, writing, etc.).

Which methods are the fastest?

Best Answer

Use the standard built-in way fs.copyFile:

const fs = require('fs');

// File destination.txt will be created or overwritten by default.
fs.copyFile('source.txt', 'destination.txt', (err) => {
  if (err) throw err;
  console.log('source.txt was copied to destination.txt');
});

If you have to support old end-of-life versions of Node.js - here is how you do it in versions that do not support fs.copyFile:

const fs = require('fs');
fs.createReadStream('test.log').pipe(fs.createWriteStream('newLog.log'));