User input in Node.js
Modern Node.js Example w/ ES6 Promises & no third-party libraries.
Rick has provided a great starting point, but here is a more complete example of how one prompt question after question and be able to reference those answers later. Since reading/writing is asynchronous, promises/callbacks are the only way to code such a flow in JavaScript.
const { stdin, stdout } = process;
function prompt(question) {
return new Promise((resolve, reject) => {
stdin.resume();
stdout.write(question);
stdin.on('data', data => resolve(data.toString().trim()));
stdin.on('error', err => reject(err));
});
}
async function main() {
try {
const name = await prompt("What's your name? ")
const age = await prompt("What's your age? ");
const email = await prompt("What's your email address? ");
const user = { name, age, email };
console.log(user);
stdin.pause();
} catch(error) {
console.log("There's an error!");
console.log(error);
}
process.exit();
}
main();
Then again, if you're building a massive command line application or want to quickly get up and running, definitely look into libraries such as inquirer.js and readlineSync which are powerful, tested options.
For those that do not want to import yet another module you can use the standard nodejs process.
function prompt(question, callback) {
var stdin = process.stdin,
stdout = process.stdout;
stdin.resume();
stdout.write(question);
stdin.once('data', function (data) {
callback(data.toString().trim());
});
}
Use case
prompt('Whats your name?', function (input) {
console.log(input);
process.exit();
});