本文翻译自:Fastest way to copy file in node.js
Project that I am working on (node.js) implies lots of operations with the file system (copying/reading/writing etc). 我正在处理的项目(node.js)暗示了文件系统的许多操作(复制/读取/写入等)。 I'd like to know which methods are the fastest, and I'd be happy to get an advice. 我想知道哪些方法是最快的,我很乐意得到建议。 Thanks. 谢谢。
#1楼
参考:https://stackoom.com/question/lO2z/在node-js中复制文件的最快方法
#2楼
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 在节点v8.5.0中,添加了copyFile
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');
});
#3楼
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;
}
}
}
#4楼
Well, usually it is good to avoid asynchronous file operations. 好吧,通常最好避免异步文件操作。 Here is the short (ie no error handling) sync example: 这是简短的(即没有错误处理)同步示例:
var fs = require('fs');
fs.writeFileSync(targetFile, fs.readFileSync(sourceFile));
#5楼
Mike Schilling's solution with error handling with a short-cut for the error event handler. Mike Schilling的错误处理解决方案,带有错误事件处理程序的快捷方式。
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;
}
}
}
#6楼
I was not able to get the createReadStream/createWriteStream
method working for some reason, but using fs-extra
npm module it worked right away. 由于某种原因,我无法使createReadStream/createWriteStream
方法起作用,但是使用fs-extra
npm模块可以立即起作用。 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');