What is the best way to accept a series of command line inputs in nodejs synchronously ?
like the program will print
Enter Value for variable one
then the user enters value, after that the command line should ask for second input like
Enter Value for variable two
and so on
The easiest way to do this, IMHO is showing "questions" to the user and waiting to his answers. Those questions can be always the same (a prompt like ">>") or maybe different (if you want to ask for some variables, for instance).
To show these questions you can use stdio. It is a module that simplifies standard input/output management, and one of its main features is precisely 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'll se 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 stdio
creator. :-)
Depending on your specific needs, you could create your own REPL.
http://nodejs.org/api/repl.html
Just call repl.start()
with options for prompt
, and use your own custom eval
and writer
callbacks.
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
}
});