press any key to continue in nodejs

In node.js 7.6 and later you can do this:

const keypress = async () => {
  process.stdin.setRawMode(true)
  return new Promise(resolve => process.stdin.once('data', () => {
    process.stdin.setRawMode(false)
    resolve()
  }))
}

;(async () => {

  console.log('program started, press any key to continue')
  await keypress()
  console.log('program still running, press any key to continue')
  await keypress()
  console.log('bye')

})().then(process.exit)

Or if you want CTRL-C to exit the program but any other key to continue normal execution, then you can replace the "keypress" function above with this function instead:

const keypress = async () => {
  process.stdin.setRawMode(true)
  return new Promise(resolve => process.stdin.once('data', data => {
    const byteArray = [...data]
    if (byteArray.length > 0 && byteArray[0] === 3) {
      console.log('^C')
      process.exit(1)
    }
    process.stdin.setRawMode(false)
    resolve()
  }))
}

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));

The accepted solution waits asynchronously for a key event and then exits, it is not really a solution to "Press any key to continue".

I needed to pause while writing some nodejs shell scripts. I ended up using the spawnSync of the child_process with the shell command "read".

This will basically pause the script and when you press Enter it will continue. Much like the pause command in windows.

require('child_process').spawnSync("read _ ", {shell: true, stdio: [0, 1, 2]});

Hope this helps.


This snippet does the job if you don't want to exit the process:

console.log('Press any key to continue.');
process.stdin.once('data', function () {
  continueDoingStuff();
});

It's async so won't work inside loop as-is-- if you're using Node 7 you could wrap it in a promise and use async/await.