Fastest way to copy file in node.js


Question

Project that I am working on (node.js) implies lots of operations with the file system (copying/reading/writing etc). I'd like to know which methods are the fastest, and I'd be happy to get an advice. Thanks.

1
429
8/11/2019 11:10:28 AM

Accepted Answer

This is a good way to copy a file in one line of code using streams:

var fs = require('fs');

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

In node v8.5.0, copyFile was added

const fs = require('fs');

// 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');
});
635
11/26/2018 9:01:58 AM

Same mechanism, but this adds error handling:

function copyFile(source, target, cb) {
  var cbCalled = false;

  var rd = fs.createReadStream(source);
  rd.on("error", function(err) {
    done(err);
  });
  var wr = fs.createWriteStream(target);
  wr.on("error", function(err) {
    done(err);
  });
  wr.on("close", function(ex) {
    done();
  });
  rd.pipe(wr);

  function done(err) {
    if (!cbCalled) {
      cb(err);
      cbCalled = true;
    }
  }
}

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon