Node.js PassThrough流未正确关闭?

时间:2016-12-15 03:18:17

标签: node.js node.js-stream

我对我的PassThrough流感到好奇,以及为什么它在我将其关闭后的资源关闭后才关闭。我使用它作为中介,一个资源需要一个ReadableStream,我需要向用户传递一个WriteableStream,以允许它们编写底层资源。起初,Duplex流看起来很理想,但需要一些实现,然后我找到了PassThrough流。

编辑:此处此问题的最佳描述:https://gist.github.com/four43/46fd38fd0c929b14deb6f1744b63026a

原始示例: 看看这个:

const fs = require('fs');
const stream = require('stream');

const passThrough = new stream.PassThrough({allowHalfOpen: false});
const writeStream = new fs.createWriteStream('/tmp/output.txt');

passThrough.pipe(writeStream)
    .on('end', () => console.log('full-end'))
    .on('close', () => console.log('full-close'))
    .on('unpipe', () => console.log('full-unpipe'))
    .on('finish', () => console.log('full-finish'));
passThrough
    .on('end', () => console.log('passThrough-end'))
    .on('close', () => console.log('passThrough-close'))
    .on('unpipe', () => console.log('passThrough-unpipe'))
    .on('finish', () => console.log('passThrough-finish'));

passThrough.end('hello world');

实际输出:

passThrough-finish
passThrough-end
full-unpipe
full-finish
full-close

似乎写作方面做了它的工作,但是"阅读" PassThrough流的一侧并没有推动关闭,即使" allowHalfOpen"选项被传递为false(我可以验证调试器中的选项)。

我是否认为这一切都错了?我如何传播writeStream的结束?

感谢。

编辑:我发现变换流也是如此,它们只是在管道关闭时才结束。有没有办法手动关闭它们? transform.end()永远不会导致流抛出" close"事件,只是"完成"和"结束"在底层资源成功之前触发的事件。

编辑2:我把这个要点放在一起:https://gist.github.com/four43/46fd38fd0c929b14deb6f1744b63026a

这告诉我,当可写完成时,可读的可写内容(可写)被正确关闭。这会让我相信,当我做transform.pipe(可写)时,它会关闭"可读"变换流的一面,因为我已经'#34;关闭"使用.end()的可写端,它应该关闭整个流。感兴趣的旁注:即使我们从未在测试2中使用它,读取也是抛弃事件。可能是一个隔离问题,但我认为我的超时等待做得非常好。

1 个答案:

答案 0 :(得分:0)

如果您想知道writeStream何时写完,那么只需在'finish'

上收听writeStream事件
const fs = require('fs');
const stream = require('stream');

const passThrough = new stream.PassThrough({allowHalfOpen: false});
const writeStream = new fs.createWriteStream('/tmp/output.txt');

passThrough
    .on('error', (err) => console.error(err))
    .on('end', () => console.log('passThrough-end'))
    .on('close', () => console.log('passThrough-close'))
    .on('unpipe', () => console.log('passThrough-unpipe'))
    .on('finish', () => console.log('passThrough-finish'));

writeStream
    .on('error', (err) => console.error(err))
    .on('close', () => console.log('full-close'))
    .on('unpipe', () => console.log('full-unpipe'))
    .on('finish', () => console.log('full-finish'));

// passThrough-finish written because all Writes are complete
passThrough.end('hello world');

passThrough.pipe(writeStream);