Skip to content

Instantly share code, notes, and snippets.

@hzhopen
Created January 26, 2016 08:06
Show Gist options
  • Save hzhopen/68537571d1ebf866cb63 to your computer and use it in GitHub Desktop.
Save hzhopen/68537571d1ebf866cb63 to your computer and use it in GitHub Desktop.
node.js异步实现大文件copy
node.js异步实现大文件copy
/*
大文件复制实例
*/
var fs = require('fs');
var path = require('path');
var out = process.stdout;
function maxCopy(srcPath, destPath) {
//读入文件流
var readStream = fs.createReadStream(srcPath);
//写入文件流
var writeStream = fs.createWriteStream(destPath);
//文件类型,大小等信息
var stat = fs.statSync(srcPath);
var totalSize = stat.size;
var passedLength = 0;
var lastSize = 0;
var startTime = Date.now();
readStream.on('data', function (chunk) {
passedLength += chunk.length;
if (writeStream.write(chunk) === false) {
readStream.pause();
}
});
//流读取结束
readStream.on('end', function () {
writeStream.end();
});
//流写入成功,则唤醒读取流
writeStream.on('drain', function () {
readStream.resume();
});
setTimeout(function show() {
var percent = Math.ceil((passedLength / totalSize) * 100);
var size = Math.ceil(passedLength / 1000000);
var diff = size - lastSize;
lastSize = size;
out.clearLine();
out.cursorTo(0);
out.write('已完成' + size + 'MB, ' + percent + '%, 速度:' + diff * 2 + 'MB/s');
if (passedLength < totalSize) {
setTimeout(show, 500);
} else {
var endTime = Date.now();
console.log();
console.log('共用时:' + (endTime - startTime) / 1000 + '秒。');
}
}, 500);
}
maxCopy('D:\\temp\\20150727升级包.rar','d:\\a.rar');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment