Node.Js之【Stream 之复制文件问题】
var fs = require('fs'), path = require('path'), out = process.stdout; var filePath = 'F:/IMG_0221.MOV'; var readStream = fs.createReadStream(filePath); var writeStream = fs.createWriteStream('file.MOV'); var stat = fs.statSync(filePath); 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; out.clearLine(); out.cursorTo(0); out.write('已完成' + size + 'MB,'+ percent +'%,速度:'+ diff*2 +'MB/s'); if(passedLength < totalSize){ setTimeout(show, 50); }else{ var endTime = Date.now(); console.log(); console.log('共用时:' + (endTime -startTime) / 1000 + '秒。'); } }, 500)