How to close a readable stream in Node.js?
var input = fs.createReadStream(\'lines.txt\');
input.on(\'data\', function(data) {
// after closing the strea
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