Best way to accept command line input synchronously in nodejs?

What is the best way to simultaneously accept a number of command line inputs in nodejs?

how the program will output

Enter Value for variable one 

then the user enters a value, after which the second input should be requested on the command line, for example

 Enter Value for variable two 

etc.

+4
source share
2 answers

The easiest way to do this, IMHO will show the "questions" to the user and is waiting for an answer. These questions can always be the same (a hint like "→") or, possibly, another (if you want, for example, to request some variables).

You can use stdio to show these questions. This is a module that simplifies standard I / O control, and one of its main functions is exactly what you want:

 var stdio = require('stdio'); stdio.question('What is your name?', function (err, name) { stdio.question('Are you male or female?', ['male', 'female'], function (err, sex) { console.log('Your name is "%s". You are "%s"', name, sex); }); }); 

If you run the previous code, you will see something like this:

 What is your name?: John Are you male or female? [male/female]: female Your name is "john". You are "female" 

stdio includes support for retries if you specify a group of possible answers. Otherwise, users will be able to write whatever they want.

PD: I'm the creator of stdio . stdio

NPM

+3
source

Depending on your specific needs, you can create your own REPL.

http://nodejs.org/api/repl.html

Just call repl.start() with the parameters for prompt and use your own calls to eval and writer .

 repl.start({ prompt: 'Enter value: ', eval: function (cmd, context, filename, callback) { // Do something callback(/* return value goes here */); }, writer: function (data) { // echo out data to the console here } }); 
0
source

Source: https://habr.com/ru/post/1448066/


All Articles