我可以在管道中使用writeStream.bytesWritten吗?

时间:2018-05-22 11:11:44

标签: javascript node.js stream fs

我希望能够使用node.js和pipe方法监控副本的速度,以便我可以显示进度条,速度指示器以及最终的时间估算。

目前,在查看一些参考文献时,我认为我必须使用writeStream.bytesWritten,但我不确定如何正确使用它:它是否适用于{ {1}}?或者我必须使用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),如下所示:

  

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

1 个答案:

答案 0 :(得分: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);

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