Skip to content

Instantly share code, notes, and snippets.

@unitycoder
Created December 21, 2017 05:18
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save unitycoder/8eade8271b44e1bf9ac149e5d7ad566b to your computer and use it in GitHub Desktop.
Save unitycoder/8eade8271b44e1bf9ac149e5d7ad566b to your computer and use it in GitHub Desktop.
node.js Wait For KeyPress in console
// node.js get keypress
var stdin = process.stdin;
// without this, we would only get streams once enter is pressed
//stdin.setRawMode( true );
// resume stdin in the parent process (node app won't quit all by itself
// unless an error or process.exit() happens)
stdin.resume();
// i don't want binary, do you?
stdin.setEncoding( 'utf8' );
// on any data into stdin
stdin.on( 'data', function( key )
{
// ctrl-c ( end of text )
if ( key === '\u0003' ) {
process.exit();
}
// without rawmode, it returns EOL with the string
if (key.indexOf('1')==0)
{
console.log("press 1");
}
if (key.indexOf('2')==0)
{
console.log("press 2");
}
// write the key to stdout all normal like
// process.stdout.write( key );
});
@J-Cake
Copy link

J-Cake commented Oct 13, 2018

With rawmode, none of the inbuilt keyboard-shortcuts like CTRL+C and ALT+F4 don't work anymore, is there an override for this?

@ilanolkies
Copy link

@KlaussMC if(key.ctrl && ...)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment