Ionică Bizău Ionică Bizău - 4 months ago 19x
Node.js Question

How to close a readable stream (before end)?

How to close a readable stream in Node.js?

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

input.on('data', function(data) {
// after closing the stream, this will not
// be called again

if (gotFirstLine) {
// close this stream and continue the
// instructions from this if

This would be better than:

input.on('data', function(data) {
if (isEnded) { return; }

if (gotFirstLine) {
isEnded = true;

But this would not stop the reading process...


Invoke input.close(). It's not in the docs, but

clearly does the job :) It actually does something similar to your isEnded.

EDIT 2015-Apr-19 Based on comments below, and to clarify and update:

  • This suggestion is a hack, and is not documented.
  • Though for looking at the current lib/fs.js it still works >1.5yrs later.
  • I agree with the comment below about calling destroy() being preferable.
  • As correctly stated below this works for fs ReadStreams's, not on a generic Readable

As for a generic solution: it doesn't appear as if there is one, at least from my understanding of the documentation and from a quick look at _stream_readable.js.

My proposal would be put your readable stream in paused mode, at least preventing further processing in your upstream data source. Don't forget to unpipe() and remove all data event listeners so that pause() actually pauses, as mentioned in the docs