Accept input from the command line in Node
How to make a Node.js CLI program interactive using the built-in readline Node module
How to make a Node.js CLI program interactive?
Node since version 7 provides the readline
module to perform exactly this: get input from a readable stream such as the process.stdin
stream, which during the execution of a Node program is the terminal input, one line at a time.
const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout
})
readline.question(`What's your name?`, (name) => {
console.log(`Hi ${name}!`)
readline.close()
})
This piece of code asks the username, and once the text is entered and the user presses enter, we send a greeting.
The question()
method shows the first parameter (a question) and waits for the user input. It calls the callback function once enter is pressed.
In this callback function, we close the readline interface.
readline
offers several other methods, and Iโll let you check them out on the package documentation I linked above.
If you need to require a password, itโs best to not echo it back, but instead showing a *
symbol.
The simplest way is to use the readline-sync
package which is very similar in terms of the API and handles this out of the box.
A more complete and abstract solution is provided by the Inquirer.js package.
You can install it using npm install inquirer
, and then you can replicate the above code 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 lets you do many things like asking multiple choices, having radio buttons, confirmations, and more.
Itโs 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.
THE VALLEY OF CODE
THE WEB DEVELOPER's MANUAL
You might be interested in those things I do:
- Learn to code in THE VALLEY OF CODE, your your web development manual
- Find a ton of Web Development projects to learn modern tech stacks in practice in THE VALLEY OF CODE PRO
- I wrote 16 books for beginner software developers, DOWNLOAD THEM NOW
- Every year I organize a hands-on cohort course coding BOOTCAMP to teach you how to build a complex, modern Web Application in practice (next edition February-March-April-May 2024)
- Learn how to start a solopreneur business on the Internet with SOLO LAB (next edition in 2024)
- Find me on X