← Back to Node.js, page 6

nodejs-0110 · Easy fresher

How do you stream newline-delimited JSON (NDJSON) in Node.js, and how do you handle bad lines?

NDJSON stores one JSON value per line, so you can read and write it as a stream without holding everything in memory. Read with readline (or a line splitter), call JSON.parse inside try/catch for each line, and record the line number of bad lines. Write by calling JSON.stringify(item) + '\n'. A normal JSON array must be parsed completely before use.

Full answer

A JSON array is one value. JSON.parse needs the whole text, so a 2 GB file needs 2 GB or more of memory. NDJSON (also JSON Lines, .jsonl) puts one complete JSON value on each line. Each line stands alone, so you can process it as soon as it arrives.

Reading:

  • Use readline.createInterface({ input }) and for await (const line of rl). readline handles chunk boundaries and \r\n.
  • Parse each line with JSON.parse in try/catch. One bad line should not stop a job that has millions of lines. Count the failures and save the line number and a short sample for review.
  • Skip empty lines (a trailing newline is common).
  • Cap the line length if the input is untrusted.

Writing:

  • Write JSON.stringify(item) + '\n' for each item. JSON.stringify never puts a raw newline inside a string, because newlines in strings are escaped, so one item stays on one line.
  • Use a Writable stream and respect backpressure (pipeline with a generator is simple).

Where it is used: log files, exports from databases and search engines, streaming API responses such as event feeds, and bulk import formats.

Compare with alternatives: CSV is smaller but flat, and Server-Sent Events adds framing for browsers. For one huge JSON array you need a streaming parser library, which is more complex, so prefer NDJSON when you control the format.

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

// Input arrives in arbitrary pieces, and line 3 is damaged.
const pieces = [
  '{"name":"Asha","marks":78}\n{"name":"Ra',
  'vi","marks":64}\n{"name":"Meera","marks":\n',
  '\n{"name":"Kabir","marks":91}',
];

async function main() {
  const rl = readline.createInterface({ input: Readable.from(pieces), crlfDelay: Infinity });
  const good = [];
  const bad = [];
  let lineNumber = 0;
  for await (const line of rl) {
    lineNumber++;
    if (!line.trim()) continue;                      // skip empty lines
    try {
      good.push(JSON.parse(line));
    } catch (err) {
      bad.push({ line: lineNumber, sample: line.slice(0, 20) });
    }
  }
  console.log('parsed:', good.map((r) => r.name).join(', '));
  console.log('bad lines:', JSON.stringify(bad));

  // Writing NDJSON: one stringify per line. A newline inside a value is escaped.
  const out = [];
  await pipeline(
    Readable.from(good.concat({ name: 'Zoya\nTwo', marks: 55 })),
    async function* (source) { for await (const item of source) yield JSON.stringify(item) + '\n'; },
    async function (source) { for await (const text of source) out.push(text); },
  );
  console.log('output lines:', out.join('').trimEnd().split('\n').length);
  console.log('last line:', out[out.length - 1].trimEnd());
}
main();

The input is split in awkward places and one line is broken. The good lines are parsed and the bad line is reported by number. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): parsed: Asha, Ravi, Kabir bad lines: [{"line":3,"sample":"{\"name\":\"Meera\",\"mar"}] output lines: 4 last line: {"name":"Zoya\nTwo","marks":55}

Key points

  • NDJSON is one JSON value per line, so it streams.
  • Parse each line separately and keep going after a bad line.
  • JSON.stringify escapes newlines, so one item is one line.
  • readline handles chunk boundaries.

Common mistakes

  • Reading the whole file and using JSON.parse on a single array.
  • Letting one bad line crash the whole job.
  • Splitting on '\n' by hand and ignoring chunk boundaries.
  • Pretty-printing JSON, which puts one value on many lines.
  • Not skipping the empty last line.

Follow-ups

  • How is NDJSON different from a JSON array in an HTTP API?
  • How would you limit the maximum line size?
  • How would you stream a large JSON array without NDJSON?

Tips

  • Say 'one value per line' in the first sentence.
  • Mention bad line handling.
  • Compare with a JSON array.