press any key to continue in nodejs

45,474

Solution 1

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

Solution 2

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()
  }))
}

Solution 3

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.

Solution 4

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.

Solution 5

There is a package for this: press-any-key

And here is an example:

const pressAnyKey = require('press-any-key');
pressAnyKey("Press any key to resolve, or CTRL+C to reject", {
  ctrlC: "reject"
})
  .then(() => {
    console.log('You pressed any key')
  })
  .catch(() => {
    console.log('You pressed CTRL+C')
  })

It runs without problems in W10.

Share:
45,474
Barterio
Author by

Barterio

Updated on June 23, 2021

Comments

  • Barterio
    Barterio about 3 years

    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?

  • Jake Sellers
    Jake Sellers about 10 years
    This is not a solution to the question, this kills the program on a keypress, the question was to pause and then resume on a keypress.
  • hellboy
    hellboy about 9 years
    I got in process.stdin.setRawMode(true) TypeError: Object #<Socket> has no method 'setRawMode'
  • Stop Slandering Monica Cellio
    Stop Slandering Monica Cellio over 8 years
    Paktc does not work at all, it depends on a global called v8debug which don't care to research, but it's not in a normal node environment.
  • justin.m.chase
    justin.m.chase over 8 years
    It's only there when a debugger is actually attached. Just tried it again in node 5, still works.
  • justin.m.chase
    justin.m.chase over 8 years
    Meaning if you run node --debug it will only open the debugger port but will not necessarily debug unless you attach something to it. If you do, instead node --debug-brk then it will actually break when the process launches and attach a console debugger to it. At that point the global v8debug variable is found.
  • Guilhem Fry
    Guilhem Fry almost 7 years
    You have to put process.stdin.setRawMode=true instead of function
  • James Wilkins
    James Wilkins almost 6 years
    If using the latest TypeScript version, select ES6 for tsconfig,json and change then(process.exit) to then(()=>process.exit(0)).
  • justin.m.chase
    justin.m.chase almost 5 years
    Lol, no. You'd have to clear the require cache and then require it again obviously. But seriously this was my first npm library and it's terrible, lol. But I learned a lot.
  • orad
    orad over 4 years
    For Windows replace "read _ " with "pause". I check process.platform to set it based on the platform.
  • n370
    n370 over 4 years
    Watch out if you're using nodemon!! process.stdin.setRawMode may be undefined.
  • Ruslan
    Ruslan about 4 years
    This is UNIX-only
  • Hugo Aboud
    Hugo Aboud over 2 years
    For some reason the program was exiting at the process.stdin.once call. Adding the process.stdin.resume() after setRawMode(true), as suggested on @vkurchatkin answer, solved it. (Node 14.16.0)
  • teleme.io
    teleme.io over 2 years
    simple and elegant