【问题标题】:Should I close ReadStream after using .pipe() method使用 .pipe() 方法后我应该关闭 ReadStream
【发布时间】:2017-04-04 08:50:17
【问题描述】:

我正在使用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

一个重要的警告是,如果 Readable 流发出错误 在处理过程中,Writable 目标未关闭 自动地。如果发生错误,则需要手动 关闭每个流以防止内存泄漏。

所以我有两个问题:

  1. 我应该完全关闭 Node JS 中的可读和可写流吗? (手动,使用try-finally 块)。还是自动关闭流?

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

【问题讨论】:

    标签: node.js


    【解决方案1】:

    如果你正在使用管道事件,那么你可以使用 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) 我应该关闭 Node JS 中的可读可写流吗? (手动,使用 try-finally 块)。或流关闭 自动?

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

    无论是否使用 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');
        });
    

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

    【讨论】:

    • 谢谢,我稍微编辑了我的问题,使其更有条理。你能回答我的两个问题吗?
    • 我错误地认为在pipe 之后立即调用unpipe 会导致提前关闭管道,但事实并非如此。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-05
    • 1970-01-01
    • 2012-03-23
    • 2014-02-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多