Skip to main content
How do you make a Node.js CLI program interactive? Node.js since version 7 provides the readline module to do exactly this: get input from a readable stream such as the process.stdin stream, which during the execution of a Node.js program is the terminal input, one line at a time.
import readline from 'node:readline';

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

rl.question(`What's your name?`, name => {
  console.log(`Hi ${name}!`);
  rl.close();
});
This code asks the user’s name, and once the text is entered and the user presses enter, it sends a greeting. The question() method shows the first parameter (a question) and waits for user input. It calls the callback function once enter is pressed. In this callback function, the readline interface is closed.
readline offers several other methods. Check them out in the package documentation.
If you need to prompt for a password, it’s best not to echo it back, but instead show a * symbol.

Build docs developers (and LLMs) love