TExcelTAD
Home › Node.js › Node.js Readline

Node.js Readline

The node:readline module reads a stream one line at a time. It is the standard way to build interactive command-line prompts and to process large text files (logs, CSV exports) without loading them into memory all at once.

There are two flavours:

Import Style
node:readline callback and event based, plus async iteration
node:readline/promises rl.question() returns a promise — best for prompts

Asking the user a question

An interactive prompt reads from process.stdin and writes to process.stdout. Because the playground can't type for you, this example is shown as a script plus a simulated terminal session:

js
// ask.mjs
import * as readline from 'node:readline/promises';
import { stdin as input, stdout as output } from 'node:process';

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

const name = await rl.question('What is your name? ');
const age = Number(await rl.question('How old are you? '));
console.log(`Hello ${name}, next year you will be ${age + 1}.`);

rl.close(); // without this the program keeps waiting for input
bash · try it yourself
node ask.mjs
What is your name? Ada
How old are you? 36
Hello Ada, next year you will be 37.

Note: Always call rl.close() when you're done. An open interface keeps the stdin stream alive and your program never exits.

Reading lines from any stream

createInterface() accepts any readable stream as input. Below we build one from an array of text chunks with Readable.from(). Notice that the chunks don't line up with the line breaks — readline takes care of splitting and joining them:

node · try it yourself
const readline = require('node:readline');
const { Readable } = require('node:stream');

const input = Readable.from(['first li', 'ne\nsecond line\nthi', 'rd line\n']);
const rl = readline.createInterface({ input, crlfDelay: Infinity });

let n = 0;
rl.on('line', (line) => {
  n++;
  console.log(`${n}: ${line}`);
});
rl.on('close', () => console.log(`Read ${n} lines`));
1: first line
2: second line
3: third line
Read 3 lines

crlfDelay: Infinity makes Windows line endings (\r\n) count as a single line break.

Async iteration with for await

The interface is also an async iterable, which leads to very readable code. This is the recommended pattern for processing a file line by line:

node · try it yourself
const fs = require('node:fs');
const readline = require('node:readline');

fs.writeFileSync('sales.csv', 'region,amount\nnorth,120\nsouth,80\nnorth,45\n');

async function main() {
  const rl = readline.createInterface({
    input: fs.createReadStream('sales.csv'),
    crlfDelay: Infinity,
  });

  const totals = {};
  let header = true;
  for await (const line of rl) {
    if (header) { header = false; continue; }
    const [region, amount] = line.split(',');
    totals[region] = (totals[region] ?? 0) + Number(amount);
  }
  console.log(totals);
  fs.unlinkSync('sales.csv');
}
main();
{ north: 165, south: 80 }

Because the file is streamed, the same code works for a 5 GB log file using only a few kilobytes of memory.

Useful interface members

Member Purpose
rl.question(query) print query, resolve with the next line (promises API)
rl.on('line', fn) called for every complete line
rl.on('close', fn) input ended or rl.close() was called
rl.setPrompt(str) / rl.prompt() show a custom prompt like >
rl.close() stop reading and release the input
for await (const line of rl) iterate over lines asynchronously

A tiny REPL-style loop

Combining prompt() and the line event gives you a mini shell. Here the "user input" comes from a stream again, so the run is repeatable (the prompt is written to stdout without a newline, so it appears in front of each answer):

node · try it yourself
const readline = require('node:readline');
const { Readable } = require('node:stream');

const rl = readline.createInterface({
  input: Readable.from(['add 2 3\n', 'mul 4 5\n', 'quit\n']),
  output: process.stdout,
  terminal: false,
});

rl.setPrompt('> ');
rl.on('line', (line) => {
  const [cmd, a, b] = line.trim().split(' ');
  if (cmd === 'quit') return rl.close();
  const result = cmd === 'add' ? Number(a) + Number(b) : Number(a) * Number(b);
  console.log(`${line} = ${result}`);
});
rl.on('close', () => console.log('bye'));
add 2 3 = 5
mul 4 5 = 20
bye

Tip: For a real interactive tool, call rl.prompt() once at the start and again at the end of each line handler.

Test yourself

Why should you call rl.close() after reading user input?

  1. To save the input to a file
  2. Otherwise the open stdin keeps the program running
  3. To clear the screen
  4. It is required before calling question()

Which import gives you a question() method that returns a promise?

  1. node:readline/promises
  2. node:stream/promises
  3. node:util
  4. node:fs/promises

What is the main benefit of reading a big file with readline and for await?

  1. It is the only way to read text
  2. Lines are processed as they stream in, keeping memory use low
  3. It decompresses the file
  4. It sorts the lines