Skip to content
jshacks.dev
Node.js

How to Prompt for Input in a Node.js CLI

Ask questions in a Node.js command line tool with readline/promises: defaults, yes or no, validation loops, hidden input and piped stdin.

8 min read
Summarize in AI
Flat illustration of a terminal session, with the Node.js, Linux, Ubuntu and GNU Bash logos.

A command line tool that cannot ask a question is stuck with flags for everything, and a tool that asks too many questions cannot be scripted. The right design is both: flags for automation, prompts for a person at a keyboard. Node.js has the pieces built in. The node:readline/promises module reads a line from standard input and resolves a promise with the answer, and a few patterns on top of it give you defaults, confirmations, validation and hidden input for secrets. This post builds each pattern, shows the exact terminal transcript for each, and explains what changes when standard input is not a terminal. It targets Node.js 26 and uses an API that has been stable since Node.js 17.

The first question

readline.createInterface() takes an input stream and an output stream. For a terminal tool those are process.stdin and process.stdout. The interface's question() method prints a prompt and returns a promise for the line the user types. The [readline promises API](https://nodejs.org/api/readline.html#promises-api) describes the interface and its events.

ask.jsJavaScript
import { createInterface } from "node:readline/promises";
import { stdin as input, stdout as output } from "node:process";

const rl = createInterface({ input, output });

const name = await rl.question("What is your name? ");
console.log(`Hello, ${name}!`);

rl.close();

Here is the transcript. The text after the question mark is what the user typed, and the press of Enter ends the line.

Text
What is your name? Ada
Hello, Ada!

Calling rl.close() matters. An open interface keeps process.stdin flowing, and the process does not exit while it is reading, so a script that forgets to close it hangs after the last question. Closing in a finally block makes that robust, which the later examples do.

Defaults and trimming

A prompt with a sensible default saves keystrokes. Show the default in brackets, and use it when the answer is empty. Trim the input as well, because a stray space is the most common cause of a surprising value.

with-default.jsJavaScript
import { createInterface } from "node:readline/promises";
import { stdin as input, stdout as output } from "node:process";

export async function ask(rl, question, fallback = "") {
  const suffix = fallback ? ` [${fallback}]` : "";
  const answer = (await rl.question(`${question}${suffix}: `)).trim();
  return answer === "" ? fallback : answer;
}

const rl = createInterface({ input, output });
try {
  const project = await ask(rl, "Project name", "my-app");
  const port = await ask(rl, "Port", "3000");
  console.log({ project, port });
} finally {
  rl.close();
}
Text
Project name [my-app]: 
Port [3000]: 8080
{ project: 'my-app', port: '8080' }

The first prompt was answered with only Enter, so the default applied. All answers are strings, so convert the port to a number where you use it.

Yes or no questions

A confirmation is a question with a fixed set of acceptable answers. Accept the common ones in any letter case, make the default visible with a capital letter, and treat anything else as a reason to ask again.

confirm.jsJavaScript
import { createInterface } from "node:readline/promises";
import { stdin as input, stdout as output } from "node:process";

export async function confirm(rl, question, defaultYes = false) {
  const hint = defaultYes ? "Y/n" : "y/N";
  while (true) {
    const answer = (await rl.question(`${question} (${hint}) `)).trim().toLowerCase();
    if (answer === "") return defaultYes;
    if (["y", "yes"].includes(answer)) return true;
    if (["n", "no"].includes(answer)) return false;
    console.log("Please answer y or n.");
  }
}

const rl = createInterface({ input, output });
try {
  const go = await confirm(rl, "Delete the build directory?");
  console.log(go ? "Deleting." : "Cancelled.");
} finally {
  rl.close();
}
Text
Delete the build directory? (y/N) maybe
Please answer y or n.
Delete the build directory? (y/N) y
Deleting.

For destructive actions the default is no, so pressing Enter by habit does nothing harmful. That convention is worth following in every tool you write.

Validation loops

When a value must meet a rule, loop until it does and say what was wrong. Pass the rule as a function that returns an error message, or nothing when the value is acceptable.

validate.jsJavaScript
import { createInterface } from "node:readline/promises";
import { stdin as input, stdout as output } from "node:process";

export async function askValid(rl, question, check) {
  while (true) {
    const answer = (await rl.question(`${question}: `)).trim();
    const problem = check(answer);
    if (!problem) return answer;
    console.log(`  ${problem}`);
  }
}

const rl = createInterface({ input, output });
try {
  const port = await askValid(rl, "Port (1024-65535)", (value) => {
    const n = Number(value);
    if (!Number.isInteger(n)) return "Enter a whole number.";
    if (n < 1024 || n > 65535) return "Port must be between 1024 and 65535.";
  });
  console.log("Using port", Number(port));
} finally {
  rl.close();
}
Text
Port (1024-65535): abc
  Enter a whole number.
Port (1024-65535): 80
  Port must be between 1024 and 65535.
Port (1024-65535): 8080
Using port 8080

An empty string passes Number("") as 0, which is an integer, so it falls through to the range message. That is acceptable here, and a separate check for an empty answer would give a clearer message if your tool needs one.

A menu of choices

For a short list, print numbered options and ask for the number. It is easier to type than an exact word, and it validates with the same loop.

choose.jsJavaScript
import { createInterface } from "node:readline/promises";
import { stdin as input, stdout as output } from "node:process";

export async function choose(rl, question, options) {
  console.log(question);
  options.forEach((option, index) => console.log(`  ${index + 1}) ${option}`));
  while (true) {
    const n = Number((await rl.question("Choice: ")).trim());
    if (Number.isInteger(n) && n >= 1 && n <= options.length) return options[n - 1];
    console.log(`Enter a number from 1 to ${options.length}.`);
  }
}

const rl = createInterface({ input, output });
try {
  const template = await choose(rl, "Pick a template:", ["minimal", "api", "cli"]);
  console.log("Selected", template);
} finally {
  rl.close();
}
Text
Pick a template:
  1) minimal
  2) api
  3) cli
Choice: 4
Enter a number from 1 to 3.
Choice: 3
Selected cli

Hiding input for secrets

A password typed into question() is echoed to the screen. Hiding it needs a small trick: put the terminal in raw mode and read the keystrokes yourself, without echoing them. Raw mode only exists on a TTY, so the function must check isTTY first.

secret.jsJavaScript
import { stdin, stdout } from "node:process";

export function askSecret(question) {
  return new Promise((resolve, reject) => {
    if (!stdin.isTTY) {
      reject(new Error("Cannot hide input when stdin is not a terminal"));
      return;
    }
    stdout.write(question);
    stdin.setRawMode(true);
    stdin.resume();
    stdin.setEncoding("utf8");

    let value = "";
    const onData = (key) => {
      if (key === "\r" || key === "\n") {
        stdin.setRawMode(false);
        stdin.pause();
        stdin.off("data", onData);
        stdout.write("\n");
        resolve(value);
      } else if (key === "\u0003") {
        stdin.setRawMode(false);
        stdout.write("\n");
        process.exit(130);
      } else if (key === "\u007f") {
        value = value.slice(0, -1);
      } else {
        value += key;
      }
    };
    stdin.on("data", onData);
  });
}

const password = await askSecret("Password: ");
console.log(`Read ${password.length} characters`);
Text
Password: 
Read 8 characters

Typing eight characters shows nothing on screen. Raw mode turns off the terminal's own handling of Ctrl+C, so the code above handles the byte \u0003 itself and exits with status 130, the conventional code for a script ended by SIGINT. Pasted text arrives in one data event with many characters, and the simple loop appends it as a whole, which is fine for this purpose. If you need arrow keys, history or editing within the line, use a prompt library instead.

When stdin is not a terminal

A tool that asks questions blocks forever, or reads the wrong data, when it runs in a pipeline or in CI. Check process.stdin.isTTY before prompting, and fall back to a flag, an environment variable or a clear error. Two behaviours are worth knowing.

First, when input is piped, question() reads lines from the pipe in order, which is handy for testing: printf 'Ada\n8080\n' | node with-default.js answers both questions without a human.

Second, when the pipe ends before an answer arrives, the interface closes with nothing to read, and the code after the await may never run. That is why the check below belongs at the top of any tool that prompts.

non-tty.jsJavaScript
import { createInterface } from "node:readline/promises";
import { stdin as input, stdout as output } from "node:process";

if (!input.isTTY) {
  console.error("This command needs a terminal. Pass --name instead.");
  process.exit(2);
}

const rl = createInterface({ input, output });
try {
  console.log("Hello,", await rl.question("Name: "));
} finally {
  rl.close();
}
Text
This command needs a terminal. Pass --name instead.

That output appears when you run echo Ada | node non-tty.js. A tool built on this check behaves well in both worlds: interactive for a person, explicit for a script.

Cancelling with Ctrl+C

The interface emits a SIGINT event when the user presses Ctrl+C. With no listener, readline pauses the input stream instead of ending the program, which leaves the tool looking stuck. Add a handler to clean up and set a non-zero exit code.

sigint.jsJavaScript
import { createInterface } from "node:readline/promises";
import { stdin as input, stdout as output } from "node:process";

const rl = createInterface({ input, output });

rl.on("SIGINT", () => {
  console.log("\nCancelled.");
  rl.close();
  process.exitCode = 130;
});

const answer = await rl.question("Continue? ");
console.log("Answered:", answer);
rl.close();
Text
Continue? ^C
Cancelled.

Design rules for good prompts

The mechanics are small, and what separates a pleasant tool from an irritating one is a handful of design habits.

Ask only what you cannot infer. If the current directory name makes a fine project name, offer it as the default instead of asking the user to type it. Every question you can answer with a default is a keystroke saved, and a tool that asks ten questions in a row teaches people to press Enter without reading.

Offer a flag for every prompt. A user running the tool for the twentieth time wants --name my-app --yes, not a conversation, and a CI job has no one to answer. A clean structure is to parse flags first, ask a question only for a value that is still missing, and skip every prompt when a --yes or --no-input flag is present. That way the interactive path is a convenience layered over the scripted one, and both go through the same code that uses the answers.

Echo what you understood before doing anything that cannot be undone. A summary such as the project name, the port and the template, followed by one confirmation, catches a typo made three questions earlier. And keep the wording of each question specific: "Delete the build directory?" tells the user what is at stake, where "Continue?" does not.

Finally, treat the end of input as an answer. When a user presses Ctrl+D, the input stream ends, and your tool should stop with a short message and a non-zero exit code, not wait or carry on with empty strings. Returning an error from the code that reads the answer, and handling it once at the top of the program, keeps every prompt in the tool consistent.

Share

Keep reading

Flat illustration of jobs on a conveyor heading to a rack of workers, with the Node.js, JavaScript, Apache Kafka, Redis and RabbitMQ logos.
Node.js

The Node.js Event Loop Phases Explained

Learn the six phases of the Node.js event loop, where timers, I/O, setImmediate, process.nextTick and promises run, and why their order sometimes surprises you.

6 min read
Flat illustration of jobs on a conveyor heading to a rack of workers, with the Node.js, RabbitMQ, Apache Kafka, Redis and npm logos.
Node.js

What Is Node.js, and What Is It Good At?

Node.js runs JavaScript outside the browser on the V8 engine. Learn what it is, how its event loop works, where it shines, and where another tool fits better.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.