Project that I am working at (node.js) implies a lot of operations with file system (copying/reading/writing etc). I'd like to know, what methods are the fastest, and I'd be happy for some advice.
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'));
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;
}
}
}
I was not able to get the createReadStream/createWriteStream
method working for some reason, but using fs-extra
npm module it worked right away. I am not sure of the performance difference though.
npm install --save fs-extra
var fs = require('fs-extra');
fs.copySync(path.resolve(__dirname,'./init/xxx.json'), 'xxx.json');
Mike Schilling's solution with error handling with a short-cut for the error event handler.
function copyFile(source, target, cb) {
var cbCalled = false;
var rd = fs.createReadStream(source);
rd.on("error", done);
var wr = fs.createWriteStream(target);
wr.on("error", done);
wr.on("close", function(ex) {
done();
});
rd.pipe(wr);
function done(err) {
if (!cbCalled) {
cb(err);
cbCalled = true;
}
}
}
Fast to write and convenient to use, with promise and error management.
function copyFile(source, target) {
return new Promise(function(resolve, reject) {
var rd = fs.createReadStream(source);
rd.on('error', reject);
var wr = fs.createWriteStream(target);
wr.on('error', reject);
wr.on('finish', resolve);
rd.pipe(wr);
});
}
Well, usually it is good to avoid asynchronous file operations. Here is the short (i.e. no error handling) sync example:
var fs = require('fs');
fs.writeFileSync(targetFile, fs.readFileSync(sourceFile));