3

In a node program I'm reading from a file stream with fs.createReadStream. But when I pause the stream the program exits. I thought the program would keep running since the file is still opened, just not being read.

Currently to get it to not exit I'm setting an interval that does nothing.

setInterval(function() {}, 10000000);

When I'm ready to let the program exit, I clear it. But is there a better way?

Example Code where node will exit:

var fs = require('fs');

var rs = fs.createReadStream('file.js');
rs.pause();
3
  • Can we see some example code, with event handlers, etc? Commented Jan 24, 2012 at 16:52
  • An example script that recreates the problems seems essential here. Commented Jan 24, 2012 at 16:54
  • @mike jinx! you owe me a soda Commented Jan 24, 2012 at 16:54

2 Answers 2

6

Node will exit when there is no more queued work. Calling pause on a ReadableStream simply pauses the data event. At that point, there are no more events being emitted and no outstanding work requests, so Node will exit. The setInterval works since it counts as queued work.

Generally this is not a problem since you will probably be doing something after you pause that stream. Once you resume the stream, there will be a bunch of queued I/O and your code will execute before Node exits.

Let me give you an example. Here is a script that exits without printing anything:

var fs = require('fs');

var rs = fs.createReadStream('file.js');
rs.pause();

rs.on('data', function (data) {
  console.log(data); // never gets executed
});

The stream is paused, there is no outstanding work, and my callback never runs.

However, this script does actually print output:

var fs = require('fs');

var rs = fs.createReadStream('file.js');
rs.pause();

rs.on('data', function (data) {
  console.log(data); // prints stuff
});

rs.resume(); // queues I/O

In conclusion, as long as you are eventually calling resume later, you should be fine.

Sign up to request clarification or add additional context in comments.

1 Comment

This video is good for gaining a better understanding of the JavaScript event loop and how work is queued.
1

Short way based on answers below

require('fs').createReadStream('file.js').pause();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.