Fastest way to copy file in node.js
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.
这是使用流在一行代码中复制文件的好方法:
var fs = require('fs');
fs.createReadStream('test.log').pipe(fs.createWriteStream('newLog.log'));
相同的机制,但是这增加了错误处理:
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.
fs-extra
npm install --save fs-extra
var fs = require('fs-extra');
fs.copySync(path.resolve(__dirname,'./init/xxx.json'), 'xxx.json');
链接地址: http://www.djcxy.com/p/58344.html
上一篇: ReadDirectoryChangesW文件已移动解决方法
下一篇: 在node.js中复制文件的最快方法