How to Stream JSON Lines and Parse Them Incrementally
Stream JSON Lines in Node.js 24 and parse each record as it arrives, with readline, async iteration and fetch, without loading the whole response into memory.

A large JSON array has to be read to the final bracket before JSON.parse can return anything, so a 400 MB export means 400 MB in memory and a long wait for the first result. JSON Lines, also called NDJSON, solves that by putting one complete JSON value on each line. A reader can parse line one while line one thousand is still on the wire. This post shows how to stream JSON Lines and parse them incrementally in Node.js 24: from a file, from an HTTP response using fetch, and as a producer that writes records as they are ready. It also covers the three places where streaming parsers break, which are partial chunks, blank lines and bad records.
The format
JSON Lines is plain text with one rule: each line is a valid JSON value, usually an object, and lines are separated by \n. There is no surrounding array and no commas between lines.
{"id":1,"type":"signup","plan":"free"}
{"id":2,"type":"upgrade","plan":"pro"}
{"id":3,"type":"signup","plan":"free"}Because every line stands alone, you can append to a file without rewriting it, cut it with head, and split it with split. The cost is that it is not one JSON document, so a parser built for arrays will reject it.
Reading a file line by line
The node:readline module turns a readable stream into an async iterable of lines. Combined with createReadStream, memory stays small regardless of file size, because the stream reads in chunks and readline hands you one line at a time.
import { writeFile } from "node:fs/promises";
import { createReadStream } from "node:fs";
import { createInterface } from "node:readline";
await writeFile(
"events.jsonl",
[
'{"id":1,"type":"signup","plan":"free"}',
'{"id":2,"type":"upgrade","plan":"pro"}',
'{"id":3,"type":"signup","plan":"free"}',
].join("\n") + "\n"
);
const lines = createInterface({
input: createReadStream("events.jsonl", { encoding: "utf8" }),
crlfDelay: Infinity,
});
const counts = {};
for await (const line of lines) {
const event = JSON.parse(line);
counts[event.type] = (counts[event.type] ?? 0) + 1;
}
console.log(counts);{ signup: 2, upgrade: 1 }The option crlfDelay: Infinity tells readline to treat \r\n as one line break even if the two characters arrive in different chunks, which matters for files written on Windows. The loop body runs once per line and the stream applies backpressure: while your code is busy, readline stops pulling from the file.
Parsing a fetch response
The same idea works for network responses, but there is a catch. response.body is a web stream of Uint8Array chunks, and a chunk boundary can fall in the middle of a line, or even in the middle of a multi-byte character. You cannot split each chunk on newlines and parse. You have to buffer the unfinished tail.
async function* readLines(body) {
const decoder = new TextDecoder();
let buffer = "";
for await (const chunk of body) {
buffer += decoder.decode(chunk, { stream: true });
let newline;
while ((newline = buffer.indexOf("\n")) !== -1) {
yield buffer.slice(0, newline);
buffer = buffer.slice(newline + 1);
}
}
buffer += decoder.decode();
if (buffer.length > 0) yield buffer;
}
// A stand-in for response.body that splits a line across chunks.
const encoder = new TextEncoder();
async function* fakeBody() {
yield encoder.encode('{"id":1,"name":"Ad');
yield encoder.encode('a"}\n{"id":2,"na');
yield encoder.encode('me":"Grace"}\n');
}
for await (const line of readLines(fakeBody())) {
const record = JSON.parse(line);
console.log(record.id, record.name);
}1 Ada
2 GraceThree details make this correct. decoder.decode(chunk, { stream: true }) keeps a partial multi-byte character for the next call, so an emoji split across chunks is not corrupted. The while loop extracts every complete line in the buffer, because one chunk may contain several. And the final decoder.decode() plus the last check flushes a last line that has no trailing newline. In Node.js 24, response.body is async iterable, so with a real request you write readLines((await fetch(url)).body).
Tolerating bad lines
A file that is a few gigabytes long will have a bad line eventually: a truncated write, a blank line, a stray log message. Decide up front whether one bad record stops the job or is skipped and reported. For imports, skipping with a count is usually right.
function parseLines(lines) {
const records = [];
const errors = [];
lines.forEach((line, index) => {
if (line.trim() === "") return;
try {
records.push(JSON.parse(line));
} catch (error) {
errors.push({ line: index + 1, message: error.message });
}
});
return { records, errors };
}
const input = ['{"ok":true}', "", '{"broken":', '{"ok":false}'];
const { records, errors } = parseLines(input);
console.log(records.length, "records");
console.log(errors);2 records
[ { line: 3, message: 'Unexpected end of JSON input' } ]The message text comes from V8, and its wording has changed between versions, so do not match on it in code. Record the line number instead, because that is what lets someone find and fix the source row. In a streaming loop, keep a running line counter rather than an array of all lines.
Writing JSON Lines
Producing the format is simpler: serialize one object and add a newline. Never pretty-print, because a newline inside a record would split it into two broken lines. JSON.stringify without an indent argument produces a single line, and it escapes any newline characters inside string values as \n, so the output is always safe.
import { Readable } from "node:stream";
import { pipeline } from "node:stream/promises";
import { createWriteStream } from "node:fs";
import { readFile } from "node:fs/promises";
async function* records() {
for (let id = 1; id <= 3; id++) {
yield { id, note: `line one\nline two for ${id}` };
}
}
await pipeline(
Readable.from(records(), { objectMode: true }),
async function* (source) {
for await (const record of source) yield JSON.stringify(record) + "\n";
},
createWriteStream("out.jsonl")
);
const text = await readFile("out.jsonl", "utf8");
console.log(text.split("\n").length - 1, "lines");
console.log(text.split("\n")[0]);3 lines
{"id":1,"note":"line one\nline two for 1"}The record contains a real newline in the note, and the output shows it as the two characters backslash and n, so each record still occupies exactly one line. pipeline connects the three stages and handles errors and cleanup, which is why it is preferred over chaining pipe calls by hand.
Concurrency and ordering
If each record triggers an asynchronous step, such as a database insert, awaiting inside the for await loop processes them one at a time, which is safe and slow. To process several at once, collect lines into batches and run each batch with Promise.all, with a batch size matched to what the destination can take. Order within a batch is no longer guaranteed to finish in sequence, so only do this when records are independent.
Where the advice stops
JSON Lines does not help when you receive one big array you did not choose the format of. For that you need a streaming JSON tokenizer from a package, since the language has no built-in one. It also loses the single-document properties of JSON: there is no top-level metadata unless you put it on the first line by convention, and no way to know the record count without reading everything. And when each record is small and the file is a few megabytes, JSON.parse on the whole file is simpler and just as fast, so streaming is for the cases where size or latency is the problem.
Memory and backpressure in practice
The reason to stream is memory, so it is worth being precise about where memory still grows. The line reader holds one chunk plus the unfinished tail, which for typical files is tens of kilobytes. Your own code is where it grows: pushing every parsed record into an array defeats the purpose, because the array ends up as large as the file. Process each record and let it go. If you must aggregate, keep only the aggregate, such as counts per type or a running total, not the records.
Backpressure is the other half. With for await over a readable stream, the stream pauses when your loop body is slow, so a fast file cannot flood a slow database. With a hand-written reader on fetch, the same is true as long as you consume the body with for await and do not collect chunks into an array first. The failure to avoid is calling response.text() on a body that is hundreds of megabytes, which looks like streaming code and behaves like loading everything.
Resuming after a failure
Large imports fail partway: a network drop, a deploy, a database restart. Because every line is independent, you can make the job resumable by recording progress. The simplest form is a line number saved after each batch, so a restart skips that many lines before processing. For a file on disk, a byte offset is better, since you can open the stream with the start option of createReadStream and jump straight there. For a remote source, ask whether the server supports Range requests, and if it does, resume from the byte after your last complete line.
Idempotent writes make resuming safe. If the job may reprocess a few lines after a restart, key each insert on the record id with an upsert, so a second pass overwrites the first with identical data instead of creating duplicates. Without that, a resumable reader is only half a solution.


