Skip to content Skip to sidebar Skip to footer

How To Signal Eof To Node.js Stdin From Console?

I have a simple node.js app to echo stdin. When I run it interactively on the Windows console, I expected control-Z to be recognised as an EOF signal. But it isn't. So how do I

Solution 1:

the problem is you're using process.stdin.on instead of process.on()

See the fix I made here and everything should be fine and dandy :) Enjoy!

process.stdin.setEncoding('utf-8');
console.log("input is a TTY?:", process.stdin.isTTY);

process.stdin.on('readable',function() {
    var vText = process.stdin.read();
    if (vText != null)
        console.log('echo: "%s"',vText);
    process.stdout.write('> '); // prompt fornext
});

process.on('SIGINT', function() {
  console.log('Over and Out!');
  process.exit(0);
});

Also I replaced 'end' with 'SIGINT' as that's the signal that is caught by CTRL+C

You can read about the signal events here: https://nodejs.org/api/process.html#process_signal_events

Solution 2:

It would appear the solution is to use readline. This is more terminal-aware, and treats an interactive TTY ctrl-D as EOF, while also handling redirected input streams correctly. Also, being line oriented/aware, it conveniently strips newlines from the input strings.

var readline = require('readline');
process.stdin.setEncoding('utf-8');
console.log("input is a TTY?",process.stdin.isTTY);

var rl = readline.createInterface({input: process.stdin, output: process.stdout});
rl.setPrompt('> ');
rl.prompt();
rl.on('line' ,function(aText) { console.log('echo: "%s"',aText); rl.prompt(); });
rl.on('close',function()      { console.log('input has closed'); /* ... */ });

Post a Comment for "How To Signal Eof To Node.js Stdin From Console?"