How to close a readable stream (before end)?

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

提交回复
热议问题