javascriptnode.jskeypress

press any key to continue in nodejs


I need a function that will pause the execution of the script until a key is pressed. I've tried:

var stdin = process.openStdin(); 
require('tty').setRawMode(true);    

stdin.on('keypress', function (chunk, key) {
  process.stdout.write('Get Chunk: ' + chunk + '\n');
  if (key && key.ctrl && key.name == 'c') process.exit();
});

but it's just listening for a keypress and nothing happens. The program does not continue executing.

How can I pause execution?


Solution

  • Works for me:

    console.log('Press any key to exit');
    
    process.stdin.setRawMode(true);
    process.stdin.resume();
    process.stdin.on('data', process.exit.bind(process, 0));