在Node.js中使用进度信息快速复制文件?

有没有机会通过Node.js复制带有进度信息和快速的大文件?

解决scheme1 :fs.createReadStream()。pipe(…)=无用,最多比本地cp慢5

请参阅: 在node.js中复制文件的最快方法 ,可以使用进度信息(使用npm包'progress-stream'):

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

这种方式唯一的问题是它比“cp source dest”长5倍。 完整的testing代码见下面的附录。

解决scheme2 :rsync — info = progress2 =与解决scheme相同慢1 =无用

解决scheme3 :我最后的手段,使用“CoreUtils”(cp和其他人的Linux源代码)或其他函数编写node.js的本地模块,如带有进度的快速文件复制

有没有人知道比解决scheme3更好? 我想避免本机代码,但它似乎是最合适的。

谢谢! 任何包build议或提示(尝试所有fs **),欢迎!

附录:

testing代码,使用pipe道和进度:

 var path = require('path'); var progress = require('progress-stream'); var fs = require('fs'); var _source = path.resolve('../inc/big.avi');// 1.5GB var _target= '/tmp/a.avi'; var stat = fs.statSync(_source); var str = progress({ length: stat.size, time: 100 }); str.on('progress', function(progress) { console.log(progress.percentage); }); 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(str).pipe(wr); function done(err) { if (!cbCalled) { console.log('done'); cb && cb(err); cbCalled = true; } } } copyFile(_source,_target); 

更新 :一个快速(有详细的进展!)C版本在这里实现: https : //github.com/MidnightCommander/mc/blob/master/src/filemanager/file.c#L1480 。 似乎最好的去处:-)

一个可能减慢进程的方面与console.log有关。 看看这个代码:

 const fs = require('fs'); const sourceFile = 'large.exe' const destFile = 'large_copy.exe' console.time('copying') fs.stat(sourceFile, function(err, stat){ const filesize = stat.size let bytesCopied = 0 const readStream = fs.createReadStream(sourceFile) readStream.on('data', function(buffer){ bytesCopied+= buffer.length let porcentage = ((bytesCopied/filesize)*100).toFixed(2) console.log(porcentage+'%') // run once with this and later with this line commented }) readStream.on('end', function(){ console.timeEnd('copying') }) readStream.pipe(fs.createWriteStream(destFile)); }) 

以下是复制400MB文件的执行时间:

与console.log:692.950ms

无console.log:382.540ms

cpycp-file都支持progress reporting