(This page might be a bit more readable if you enable 1st-party CSS.)

Listening to standard input

While playing with input peripherals when developing the Quinix virtual machine I came across an oddity: if you start listening to stdin, your program will never terminate of its own accord, even if you stop listening:

const l = (e) => {
  console.info('hey, ', e.toString('utf-8'), '!');
  process.stdin.off('data', l);
process.stdin.on('data', l);
process.stdout.write('hi> ');

To run the above, toss it in a file listen.js and run it with node listen.js.

Normally once there’s nothing else “going on” in your Node program, it will exit. For instance, if you set a timeout for a few seconds later (at which point you print a message) and then “fall off the end”, your program will indeed wait a few seconds, print a message, and then exit. But if you start listening to stdin, that “automatic exit” once everything else is done doesn’t happen. I don’t know why; do you?

« Back