Node.js
Read a file incrementally with readline
Combine createReadStream with readline to process a text file one line at a time. This avoids collecting the complete file into one string before processing begins.
Worked example
Node.js example · save as example.mjs and run node example.mjs
import * as fs from "node:fs/promises";
import {tmpdir} from "node:os";
import {join} from "node:path";
const directory = await fs.mkdtemp(join(tmpdir(), "file-guide-"));
try {
const {createReadStream} = await import("node:fs");
const {createInterface} = await import("node:readline");
const path = join(directory, "lines.txt");
await fs.writeFile(path, "first\r\nsecond\n");
const input = createReadStream(path, {encoding: "utf8"});
const lines = createInterface({input, crlfDelay: Infinity});
try { for await (const line of lines) console.log(line); }
finally { lines.close(); input.destroy(); }
} finally {
await fs.rm(directory, {recursive: true, force: true});
}How it works
Readline recognizes line boundaries and omits the terminator from each yielded string. CrlfDelay Infinity treats CRLF as a single break regardless of timing. The finally block releases the reader when iteration ends, including early exits.
Limits and mistakes
A single extremely long line can still require substantial memory. This is a line reader, not a CSV parser that understands quoted embedded newlines. Retaining every yielded line in an array also removes the memory advantage.
Check the result
Expect first and second on separate lines. Check blank lines, CRLF input, and early loop exit when adapting the reader to a real file.
Sources
Reference documentation for the behavior used in this guide: