fent
fent

Reputation: 18205

Better way to make node not exit?

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();

Upvotes: 3

Views: 2932

Answers (2)

Dmitry Vasilev
Dmitry Vasilev

Reputation: 6508

Short way based on answers below

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

Upvotes: 1

Rohan Singh
Rohan Singh

Reputation: 21515

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.

Upvotes: 6

Related Questions