-
慕勒3428872
这是使用流在一行代码中复制文件的好方法:var fs = require('fs');fs.createReadStream('test.log').pipe(fs.createWriteStream('newLog.log'));在节点v8.5.0中,添加了copyFileconst 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');});
-
哆啦的时光机
相同的机制,但这增加了错误处理: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; } }}
-
杨__羊羊
createReadStream/createWriteStream由于某种原因,我无法使该方法正常工作,但是使用fs-extranpm模块,它可以立即工作。我不确定性能是否有所不同。fs-extranpm install --save fs-extravar fs = require('fs-extra');fs.copySync(path.resolve(__dirname,'./init/xxx.json'), 'xxx.json');