How to close a readable stream (before end)?

前端 未结 9 1238
名媛妹妹
名媛妹妹 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:53

    At version 4.*.* pushing a null value into the stream will trigger a EOF signal.

    From the nodejs docs

    If a value other than null is passed, The push() method adds a chunk of data into the queue for subsequent stream processors to consume. If null is passed, it signals the end of the stream (EOF), after which no more data can be written.

    This worked for me after trying numerous other options on this page.

    0 讨论(0)
  • 2020-11-29 03:57

    It's an old question but I too was looking for the answer and found the best one for my implementation. Both end and close events get emitted so I think this is the cleanest solution.

    This will do the trick in node 4.4.* (stable version at the time of writing):

    var input = fs.createReadStream('lines.txt');
    
    input.on('data', function(data) {
       if (gotFirstLine) {
          this.end(); // Simple isn't it?
          console.log("Closed.");
       }
    });
    

    For a very detailed explanation see: http://www.bennadel.com/blog/2692-you-have-to-explicitly-end-streams-after-pipes-break-in-node-js.htm

    0 讨论(0)
  • 2020-11-29 03:58

    This destroy module is meant to ensure a stream gets destroyed, handling different APIs and Node.js bugs. Right now is one of the best choice.

    NB. From Node 10 you can use the .destroy method without further dependencies.

    0 讨论(0)
提交回复
热议问题