How to close a readable stream (before end)?

前端 未结 9 1427
名媛妹妹
名媛妹妹 2020-11-29 03:16

How to close a readable stream in Node.js?

var input = fs.createReadStream(\'lines.txt\');

input.on(\'data\', function(data) {
   // after closing the strea         


        
9条回答
  •  野性不改
    2020-11-29 03:52

    You can't. There is no documented way to close/shutdown/abort/destroy a generic Readable stream as of Node 5.3.0. This is a limitation of the Node stream architecture.

    As other answers here have explained, there are undocumented hacks for specific implementations of Readable provided by Node, such as fs.ReadStream. These are not generic solutions for any Readable though.

    If someone can prove me wrong here, please do. I would like to be able to do what I'm saying is impossible, and would be delighted to be corrected.

    EDIT: Here was my workaround: implement .destroy() for my pipeline though a complex series of unpipe() calls. And after all that complexity, it doesn't work properly in all cases.

    EDIT: Node v8.0.0 added a destroy() api for Readable streams.

提交回复
热议问题