← Back to Node.js, page 5

nodejs-0090 · Easy fresher

How do you build interactive prompts with readline/promises, and what goes wrong with piped input?

readline/promises gives rl.question(prompt) that resolves with the user's answer. Create the interface with process.stdin and process.stdout, close it when done, and pass an AbortSignal to stop waiting. When input is piped and ends before you ask the next question, the interface closes, so use for await over the lines for piped or scripted input.

Full answer

The readline module reads input one line at a time from any readable stream, most often process.stdin.

Basic prompt with the promise API:

const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); const name = await rl.question('Name? '); rl.close();

Main features:

  • rl.question(text, { signal }) shows the prompt and resolves with the line. An AbortSignal (for example AbortSignal.timeout(10000)) cancels it.
  • rl.on('line', fn) fires for every line, with rl.setPrompt() and rl.prompt() for a loop-style shell (a REPL).
  • for await (const line of rl) reads all lines until the input ends. This is the right tool for piped input such as cat data.txt | node app.js.
  • rl.on('close') fires on Ctrl+D, Ctrl+C or when the input ends. Always close the interface, or the process waits for stdin forever.
  • history, tab completion (completer function) and line editing work when the input is a terminal. process.stdin.isTTY tells you whether it is one.
  • Passwords: readline does not hide typed characters by default. Use a muted output stream or a library for secret input.

The piped input trap: if input is a file or pipe, all lines can arrive before your code asks a question. Lines that arrive when no question is waiting are not kept for later. When the input then ends, the interface closes, and the next question() throws ERR_USE_AFTER_CLOSE. So interactive scripts that should also accept piped data must read lines with for await, or check isTTY and choose a mode.

For testing, give createInterface a PassThrough stream as input and a Writable as output, and feed the answers from the test.

javascript
const readline = require('node:readline/promises');
const { PassThrough, Writable, Readable } = require('node:stream');

async function main() {
  // 1. A scripted conversation: the "user" answers each prompt after it appears.
  const input = new PassThrough();
  const shown = [];
  const output = new Writable({ write(chunk, enc, cb) { shown.push(chunk.toString()); cb(); } });
  const rl = readline.createInterface({ input, output, terminal: false });

  const ask = (prompt, answer) => {
    const pending = rl.question(prompt);
    input.write(answer + '\n');
    return pending;
  };
  const name = await ask('Name? ', 'Asha');
  const marks = Number(await ask('Marks? ', '78'));
  rl.close();
  console.log('prompts shown:', shown);
  console.log('answers:', { name, marks });

  // 2. Cancel a question that gets no answer.
  const quiet = readline.createInterface({ input: new PassThrough(), output, terminal: false });
  const giveUp = new AbortController();
  setTimeout(() => giveUp.abort(), 20); // a normal timer keeps the process alive while we wait
  await quiet.question('Anyone there? ', { signal: giveUp.signal })
    .catch((err) => console.log('question cancelled by:', err.name));
  quiet.close();

  // 3. Piped input: read every line with for await.
  const piped = readline.createInterface({ input: Readable.from(['10\n', '20\n', '30\n']), terminal: false });
  let total = 0;
  for await (const line of piped) total += Number(line);
  console.log('sum of piped lines:', total);

  // 4. The trap: asking a question after piped input has ended.
  const late = readline.createInterface({ input: Readable.from(['only line\n']), output, terminal: false });
  await new Promise((resolve) => late.once('close', resolve));
  await late.question('Another one? ').catch((err) => console.log('question after close:', err.code)); // (error on purpose)
}

main();

The output stream is a Writable that collects the prompts, so the example runs without a keyboard. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): prompts shown: [ 'Name? ', 'Marks? ' ] answers: { name: 'Asha', marks: 78 } question cancelled by: AbortError sum of piped lines: 60 question after close: ERR_USE_AFTER_CLOSE

Key points

  • rl.question gives a promise of one answer.
  • Close the interface, or the process may not exit.
  • Piped input needs for await, not a question loop.
  • Use a PassThrough input to test prompts.

Common mistakes

  • Forgetting rl.close(), so the script never exits.
  • Using a question loop on piped input.
  • Expecting readline to hide a typed password.
  • Mixing readline and direct process.stdin listeners on the same stream.

Follow-ups

  • How would you build a small REPL with a custom prompt?
  • How do you detect that input comes from a pipe?
  • How does tab completion work with a completer function?

Tips

  • Mention close() before anything else.
  • Show you know the piped input trap.
  • Say that for await is the pipe-safe way.