The Node.js runtime
Accept input from the command line in Node
Learn how to accept input from the command line in Node.js and make CLI programs interactive using the built-in readline module and the Inquirer.js package.
You can make a Node.js CLI program interactive. Node has shipped the readline module since version 7 for exactly this job: read one line at a time from a stream such as process.stdin, which is your terminal input while the program runs.
const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout
})
readline.question(`What's your name?`, (name) => {
console.log(`Hi ${name}!`)
readline.close()
})
Run that, type a name, press Enter, and you get a greeting back. If you type Ada, the output is Hi Ada!.
The question() method prints the first argument and waits. When you press Enter, it calls the callback with your answer. We close the readline interface inside that callback so the process can exit cleanly.
Without readline.close(), the program keeps waiting for input and never exits.
readline has more methods than this. Check the package documentation I linked above when you need history, multiple prompts, or finer control.
If you need a password, do not echo the characters back. Show a * for each keystroke instead.
The readline-sync package handles that out of the box with an API very close to what you just saw.
For a richer CLI, look at Inquirer.js. Install it with npm install inquirer, then you can replicate the same flow like this:
const inquirer = require('inquirer')
var questions = [{
type: 'input',
name: 'name',
message: "What's your name?",
}]
inquirer.prompt(questions).then(answers => {
console.log(`Hi ${answers['name']}!`)
})
Inquirer.js supports multiple choices, radio buttons, confirmations, and more.
My advice: learn the built-in options first, especially readline. When your CLI grows beyond a single question, Inquirer.js is a solid next step.
It is worth knowing all the alternatives, especially the built-in ones provided by Node, but if you plan to take CLI input to the next level, Inquirer.js is an optimal choice.
Lesson completed