我能否在使用pipe时使用writeStream.bytesWritten?

4

我希望能够使用node.js和pipe方法监控复制的速度,以便显示进度条、速度指示器并最终估计时间。

目前,在查看一些参考资料时,我认为我将不得不使用writeStream.bytesWritten进行操作,但我不确定如何正确使用它:它是否与 pipe 一起工作?还是我必须使用writableStream.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),如此所述:

在每次通过循环时计算的表达式。如果条件评估为true,则重新执行语句。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/do...while

1个回答

5
我认为你正在尝试做类似这样的事情:
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);

请注意,这是异步的(非阻塞),因此如果您创建一个读取流的循环,您将尝试同时读写所有文件。


谢谢,我之前陷入困境是因为我以为读取速度可能不会与写入速度相同,但由于管道能够智能地管理流,所以它可能足够准确。我现在正在尝试使用它! - Puka
谢谢!如果您同意的话,我可能会编辑您的答案,以添加有关如何获取文件的总大小并显示复制百分比的更多细节 :) - Puka
是的,当然,随意添加任何相关细节!我想在这个单文件示例中添加 fs.statSync() 来计算进度,但决定让你自己来完成。 - Aramil Rey

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接