gpt4 book ai didi

node.js - 我应该在使用 .pipe() 方法后关闭 ReadStream

转载 作者:搜寻专家 更新时间:2023-10-31 23:40:45 25 4
gpt4 key购买 nike

我正在使用 FS#createReadStream 方法读取文件,然后使用 #pipe() 方法将其通过管道传输到一些可写流。像这样:

const stream = fs.createReadStream(...);
const transformedStream = imgStream.pipe(someTransformer).pipe(anotherTransfomer);
// do something with transformedStream

#createReadStream() 方法的文档中,我发现 it has autoClose 参数默认设置为 true

从另一边,我发现了这个 in documentation of #pipe() method :

One important caveat is that if the Readable stream emits an error during processing, the Writable destination is not closed automatically. If an error occurs, it will be necessary to manually close each stream in order to prevent memory leaks.

所以我有两个问题:

  1. 我是否应该关闭 Node JS 中的可读和可写流? (手动,使用 try-finally block )。或者流自动关闭?

  2. 还是应该仅在使用 #pipe() 方法时关闭流? (因为 #pipe() 会导致内存泄漏)

最佳答案

如果你正在使用 pipe 事件,那么你可以使用 unpipe 来结束它。

下面是使用 pipe() 和 unpipe() 事件的示例。

const writer = getWritableStreamSomehow();
const reader = getReadableStreamSomehow();
writer.on('unpipe', (src) => {
console.error('Something has stopped piping into the writer.');
assert.equal(src, reader);
});
reader.pipe(writer);
reader.unpipe(writer);

根据 node.js documentation , 当在 Readable 流上调用 stream.unpipe() 方法时会发出 'unpipe' 事件,将此 Writable 从其目标集中移除。

为了具体解决您的问题,以下是我的想法:

1) Should I close readable and writable streams in Node JS at all? (Manually, using the try-finally block). Or streams closed automatically?

2) or should I close streams only and only when I'm using #pipe() method? ( because #pipe() can result to memory leaks)

无论是否使用 pipe(),都必须关闭流。 (我也不同意你关于仅使用 pipe() 时内存泄漏问题的评论)

此外,您不能在传统的 javascript try() catch() finally() 子句中关闭流。原因是因为读写流是异步执行的。相反,您必须为他们发出结束事件。

例子:

var readStream = getReadableStreamSomehow();
readStream
.on('data', function (chunk) {
console.log(chunk);
})
.on('end', function () {
console.log('All the data in the file has been read');
})
.on('close', function (err) {
console.log('Stream has been Closed');
});

您可以为可写流发出相同的事件。

关于node.js - 我应该在使用 .pipe() 方法后关闭 ReadStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43202423/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com