【发布时间】:2018-11-01 03:17:42
【问题描述】:
我希望能够使用 node.js 和 pipe 方法监控副本的速度,以便我可以显示进度条、速度指示器并最终显示时间估计。
目前,在查看一些参考资料时,我想我必须使用writeStream.bytesWritten,但我不确定如何正确使用它:它是否适用于pipe?还是我必须使用writeableStream.write(); ?
一些背景:
由于我需要复制多个文件,我使用do ... while 循环并在每次启动副本时递增一个计数器。它工作正常,但我无法使用writeStream.bytesWritten 来监控传输率。
下面是我目前使用的代码,console.log(firstCopy.bytesWritten); 两次返回0:
//Launch copy process
do {
let readableStream = fs.createReadStream(fileList[i]);//This is the source file
let firstCopy = fs.createWriteStream(path.join(copyPathOne, fileName[i])),
secondCopy = fs.createWriteStream(path.join(copyPathTwo, fileName[i]));//These are the targets
readableStream.pipe(firstCopy);//We launch the first copy
readableStream.pipe(secondCopy);//And the second copy
console.log(firstCopy.bytesWritten);//Here we monitor the amount of bytes written
++i;//Then we increment the counter
} while (i < fileList.length);//And we repeat the process while the counter is < to the number of files
我也试过了:
console.log(writeStream.bytesWritten(firstCopy));//Error: writeStream is not defined
你为什么用do ... while而不是forEach?
我正在遍历一个数组。我本可以使用forEach,但由于我不清楚它是如何工作的,我更喜欢使用do ... while。另外,我认为复制每个文件是一种简单的方法,并且它会等待复制结束(pipe),如下所述:
每次通过循环后计算的表达式。如果条件计算结果为真,则重新执行语句。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/do...while
【问题讨论】:
标签: javascript node.js stream fs