我希望能够使用 node.js 和 pipe
方法监控副本的速度,以便我可以显示进度条、速度指示器以及最终的时间估算。
目前,在浏览一些引用资料时,我想我将不得不使用 writeStream.bytesWritten ,但我不确定如何正确使用它:does it works with 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
),如此处所述:
An expression evaluated after each pass through the loop. If condition evaluates to true, the statement is re-executed.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/do...while
最佳答案
我认为你正在尝试做这样的事情:
const wstream = fs.createWriteStream('myFileToWriteTo');
const rstream = fs.createReadStream('myFileToReadFrom');
// Every time readstream reads (Listen to stream events)
rstream.on('data', function (chunk) {
// Advance your progress by chunk.length
// progress += chunk.length
});
rstream.on('end', function () { // done
// You finished reading rstream into wstream
});
rstream.pipe(wstream);
请注意这是异步的(非阻塞的),因此如果您创建一个读取流循环,您将尝试一次读取/写入所有文件
关于javascript - 我可以将 writeStream.bytesWritten 与管道一起使用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50466246/