AI Workshop: learn to build apps with AI →
CLI and Process Management: Accept input from the command line in Node

Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.


How to make a Node.js CLI program interactive?

Node.js 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 for the user’s name, and once they press Enter, it prints 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 API documentation I linked above.

If you need to require a password, it’s best not to echo it back, but instead to show a * for each character.

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')

const 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.

Lessons in this unit:

0: Introduction
1: How to execute a shell command using Node.js
2: How to spawn a child process with Node.js
3: Node, accept arguments from the command line
4: ▶︎ Accept input from the command line in Node
5: How to log an object in Node
6: Output to the command line using Node
7: How to exit from a Node.js program