Reputation: 6587
Node.js doesn't exit automatically once a listener is set on process.stdin
, even if that listener is later removed.
Example:
const listener = ()=>{};
process.stdin.on("data", listener);
process.stdin.off("data", listener);
Upvotes: 3
Views: 958
Reputation: 6587
For some reason, Node.js waits for process.stdin
(and all other streams?) to be ended or paused before exiting. process.stdin
is initially paused, but it resumes once process.stdin.on()
is called. This can be solved by calling stream.pause()
, like this:
const listener = ()=>{};
process.stdin.on("data", listener);
process.stdin.off("data", listener);
process.stdin.pause();
Note that calling stream.end()
has no effect because it is a readable stream.
Upvotes: 0
Reputation: 707238
If you have a live listener for incoming data on stdin and that stream stays open (isn't naturally closed by coming to the end of its source), then node.js has no idea whether there is more data that may be coming or not so it keeps the process alive.
Here are several things you can do to get the app to shutdown:
Call process.exit(0)
to manually shut it down.
Call process.stdin.unref()
to tell nodejs not to wait for this stream.
Call process.stdin.pause()
.
It appears that once you've attached the data
event handler, removing it doesn't allow the app to exit (per some reports I read) so you have to resort to one of these other options.
FYI, here's a little test app where you can experiment with what causes the app to shut-down or not. I've verified that all three of these options work.
process.stdin.setRawMode(true);
process.stdin.on('data', data => {
console.log(data.toString());
if (data.toString() === 'x') {
process.stdin.pause(); // will cause process to exit
}
});
process.stdin.resume();
process.stdout.write("Type characters, 'x' to exit\n");
Upvotes: 5