Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node doesn't exit automatically once a listener is set on stdin

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);
like image 455
D. Pardal Avatar asked Nov 24 '25 23:11

D. Pardal


1 Answers

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:

  1. Call process.exit(0) to manually shut it down.

  2. Call process.stdin.unref() to tell nodejs not to wait for this stream.

  3. 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");
like image 146
jfriend00 Avatar answered Nov 27 '25 13:11

jfriend00



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!