Gas*_*hio 4 javascript stream fs node.js
我希望能够使用 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
Run Code Online (Sandbox Code Playgroud)
我也尝试过:
console.log(writeStream.bytesWritten(firstCopy));//Error: writeStream is not defined
Run Code Online (Sandbox Code Playgroud)
为什么你使用do ... while而不是forEach?
我正在遍历一个数组。我本来可以使用forEach,但由于我不清楚它是如何工作的,所以我更喜欢使用do ... while. 另外,我认为这将是复制每个文件的简单方法,并且它将等待复制结束( ),pipe如下所示:
每次通过循环后都会评估表达式。如果条件计算结果为 true,则重新执行该语句。
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);
Run Code Online (Sandbox Code Playgroud)
请注意,这是异步(非阻塞)的,因此如果您创建读取流循环,您将尝试立即读取/写入所有文件
| 归档时间: |
|
| 查看次数: |
1813 次 |
| 最近记录: |