在使用.pipe()方法后,我应该closuresReadStream

我正在使用FS#createReadStream方法读取文件,然后使用#pipe()方法将其pipe道传递给一些可写的stream。 喜欢这个:

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

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

而从另一方面来说,我在#pipe()方法的文档中find了这个:

一个重要的警告是,如果可读stream在处理期间发出错误,则可写目的地不会自动closures。 如果发生错误,则需要手动closures每个stream以防止内存泄漏。

所以我有两个问题:

  1. 我应该closuresNode JS中的可读写stream吗? (手动,使用try-finally块)。 或者stream自动closures?

  2. 或者我应该只closuresstream,只有当我使用#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 文档 ,当在可读stream上调用stream.unpipe()方法时,会发出'unpipe'事件,从其目标集中删除此Writable。

具体解决你的问题,这里是我的想法:

1)我应该closuresNode JS中的可读写stream吗? (手动,使用try-finally块)。 或者stream自动closures?

2)还是应该只closuresstream,只有当我使用#pipe()方法? (因为#pipe()可能导致内存泄漏)

无论您是否使用pipe(),您都必须closures您的stream。 (我也不同意你关于内存泄漏问题的评论,如果只使用pipe())

你也不能在传统的JavaScript try()catch()finally()子句中closuresstream。 原因是因为读写stream正在asynchronous执行。 相反,你必须发出结束事件。

例:

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

您可以发出可写入stream的相同事件。