【问题标题】:Can I use writeStream.bytesWritten with pipe?我可以将 writeStream.bytesWritten 与管道一起使用吗?
【发布时间】: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


    【解决方案1】:

    我认为你正在尝试做这样的事情:

    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);
    

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

    【讨论】:

    • 谢谢,我被卡住了,因为我认为读取可能不会以与写入相同的速度完成,但由于管道巧妙地管理流,它可能足够准确。我现在就试试看!
    • 谢谢!如果您同意,我可能会编辑您的答案,以添加有关如何获取文件总大小和显示副本百分比的更多详细信息:)
    • 是的,当然,请随时添加任何相关细节!我想添加fs.statSync() 来计算这个单个文件示例的进度,但决定由你来决定。
    猜你喜欢
    • 2020-11-27
    • 2022-07-05
    • 1970-01-01
    • 2023-03-25
    • 2020-08-04
    • 2018-10-23
    • 2011-02-22
    • 2021-03-16
    • 2016-11-20
    相关资源
    最近更新 更多