Search code examples
javascriptnode.jspromptreadline

Is there a way to pause a running script with process.stdin for user input in Node.js?


I was hoping to see if Node.js has the ability to pause a script once it hits a process.stdin block to take in user input for command-line applications, similar to how prompt() works with JS in the browser or how gets works in Ruby.

  var response = '';

  console.log("What's your favorite color?");

  process.stdin.resume();
  process.stdin.setEncoding('utf8');

  process.stdin.on('data', function (text) {
    response = text;
    process.exit();
  });

  console.log(`Cool! So ${response} is your favorite color? Mine is black.`);

In the simple script above, I would hope to see

What's your favorite color?
*pause for user input ===>* Red
Cool! So Red is your favorite color? Mine is black.

with the pause halting the script until I type something and hit enter for it to continue running. Instead, I see

What's your favorite color?
Cool! So  is your favorite color? Mine is black.

immediately printed out and THEN accepts user input from me.

I am aware there are other modules like readline and prompt that simplify taking in user input for node. For this question, I'm particularly looking to see if Node.js offers this functionality without having to install extra packages(process.stdin is the first thing that comes to mind), although it would be helpful to know if any modules provide that kind of functionality as well.


Solution

  • You can use readline-sync.

    var rl = require('readline-sync');
    var response = '';
    
    response = rl.question("What's your favorite color?");
    
    console.log(`Cool! So ${response} is your favorite color? Mine is black.`);