CLI prompts
Build interactive command-line utilities that collect user responses.
Node.js · Module
Node.js readline provides line-by-line access to a Readable stream, including process.stdin. Its promise-based API supports interactive questions with async/await.
The node:readline module reads a Readable stream one line at a time. Create an Interface with input and optional output streams, then consume lines or use the promise API to ask questions; close the interface when interaction is complete.
readline.createInterface({ input, output })| Name | Type | Description |
|---|---|---|
input | Readable | Readable stream supplying input, commonly process.stdin. |
output | Writable | Writable stream used to display prompts and terminal output. |
An Interface instance for line-oriented input and interaction.
import * as readline from 'node:readline/promises';
import { stdin as input, stdout as output } from 'node:process';
const rl = readline.createInterface({ input, output });
const answer = await rl.question('What is your name? ');
console.log(`Hello, ${answer}`);
rl.close();Creates a promise-based terminal interface, waits for one answer, prints a greeting, and closes the interface.
Build interactive command-line utilities that collect user responses.
Process incoming text streams one complete line at a time.
Use async/await for sequential terminal questions.
Use createInterface with a Readable input stream and, for terminal interaction, a writable output stream. The resulting Interface supports line-oriented reading and question prompts.
Follow-up: How would you avoid callback nesting? Use the promise-based node:readline/promises API and await question calls.
The promise API is imported from node:readline/promises. Its question method displays a query and resolves with the user's response, allowing sequential async control flow.
Follow-up: What must happen after the final question? Close the interface so it no longer keeps the process waiting for input.
Pass process.stdin as input and process.stdout as output when creating the interface. After interaction, call close on the returned Interface.
Follow-up: Can the output stream be omitted? Yes; an interface can be configured without terminal output when output is not needed.
readline/promisesreadline.createInterfaceInterfaceprocess.stdinprocess.stdout