/

Accept input from the command line in Node

Accept input from the command line in Node

Learn how to create an interactive Node.js Command Line Interface (CLI) program by utilizing the readline module in Node.js.

Making a Node.js CLI program interactive

To make a Node.js CLI program interactive, Node provides the readline module from version 7 onwards. This module allows you to retrieve input from a readable stream, such as process.stdin, line by line, which is typically the terminal input during the execution of a Node program.

1
2
3
4
5
6
7
8
9
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 code snippet prompts the user for their name and, upon receiving the input and the user hitting enter, it sends a greeting message.

The question() method displays the first parameter, which is the question, and then waits for user input. It calls the callback function once the user presses enter. In the callback function, we close the readline interface.

The readline module offers various other methods, which you can explore further in the documentation provided above.

If you need to handle password input securely by not echoing it back, you can utilize the readline-sync package. It provides a similar API and handles secure password entry out of the box.

An alternative option is the Inquirer.js package, which offers a more comprehensive and abstract solution. To use it, install it using npm install inquirer. You can then replicate the code snippet above in the following way:

1
2
3
4
5
6
7
8
9
10
11
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 provides a variety of functionalities, including multiple choice questions, radio buttons, confirmations, and more. If you plan to enhance the CLI input experience, Inquirer.js is an excellent choice.

tags: [“Node.js”, “CLI program”, “readline module”, “input”, “interactive”, “Node.js package”, “inquirer.js”, “command line interface”]