Created
December 21, 2017 05:18
-
-
Save unitycoder/8eade8271b44e1bf9ac149e5d7ad566b to your computer and use it in GitHub Desktop.
node.js Wait For KeyPress in console
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 ); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@KlaussMC
if(key.ctrl && ...)