Programming languages · Intermediate · 17 min
Process big files in Node.js with streams and pipeline
By Padding · Updated 18 Nov 2026
node:26 (Debian) · Node.js 26.13.1 LTS
You will turn a 1 GB log file into a small gzipped file of error lines with a Node.js 26 script whose memory stays flat, built from read streams, readline, a Transform, zlib and stream/promises pipeline.
On this page
Log exports, CSV dumps and database backups grow until they no longer fit comfortably in memory. The first script most people write reads the whole file with fs.readFile, works on it, and writes the result. That is fine for a few megabytes. At a gigabyte it either fails or quietly needs a gigabyte of RAM, which a small server or an older laptop does not have.
Streams fix this by moving the data through your program in small pieces. A read stream hands you about 64 KiB at a time, each piece is processed and passed on, and memory use stays roughly the same whether the file is 10 MB or 10 GB. In this tutorial you generate a 1 GB log file, watch the whole-file approach break, then build a script that keeps only the error lines and gzips them, with memory that does not grow with the file.
Everything here uses modules that ship with Node.js 26: node:fs, node:readline, node:stream, node:zlib. There is nothing to download from npm, which also helps if you are working on metered or prepaid data. The sample log includes names such as Adé and Tèmí, so you also see how to keep multi-byte UTF-8 characters intact when a file is cut into pieces.
Step 1 · Create a project and a 1 GB log file
Make a throwaway folder and confirm the Node.js version:
mkdir -p ~/streams-demo
cd ~/streams-demo
node --versionThe scripts use the .mjs extension, so Node.js treats them as ES modules and you can use import and top-level await without a package.json.
Create make-log.mjs. It writes fake web-server log lines until the file reaches the size you ask for, in megabytes. Every fiftieth line is an ERROR:
cat > make-log.mjs <<'JS'
import { createWriteStream } from 'node:fs';
import { Readable } from 'node:stream';
import { pipeline } from 'node:stream/promises';
const sizeMb = Number(process.argv[2] ?? 1024);
const output = process.argv[3] ?? 'app.log';
const targetBytes = sizeMb * 1024 * 1024;
const users = ['Ngozi', 'Kwame', 'Adé', 'Tèmí', 'Ayaan', 'Lindiwe', 'Chen', 'María'];
const paths = ['/api/orders', '/api/login', '/api/products', '/api/cart', '/health'];
const start = Date.UTC(2026, 10, 18, 8, 0, 0);
let lines = 0;
let errors = 0;
// An async generator: it produces the file one batch of 1,000 lines at a time.
async function* logLines() {
let bytes = 0;
while (bytes < targetBytes) {
let batch = '';
for (let n = 0; n < 1000; n++) {
const i = lines++;
const time = new Date(start + i * 10).toISOString();
const user = users[i % users.length];
const path = paths[i % paths.length];
if (i % 50 === 0) {
errors++;
batch += `${time} ERROR user=${user} path=${path} msg="upstream timed out after 3000 ms"\n`;
} else {
batch += `${time} INFO user=${user} path=${path} status=200 ms=${(i * 7) % 900}\n`;
}
}
bytes += Buffer.byteLength(batch);
yield batch;
}
}
await pipeline(Readable.from(logLines()), createWriteStream(output));
console.log(`wrote ${output}: ${lines} lines, ${errors} errors`);
JSTwo stream ideas already appear here, and you come back to both later. Readable.from() turns the async generator into a readable stream: each yield becomes one chunk. pipeline() connects that stream to a file write stream and waits until the last byte is on disk. The generator only runs when the file stream asks for more, so the script never builds the whole gigabyte in memory, even while it writes one.
Generate the file. It takes ten to thirty seconds depending on your disk:
node make-log.mjs
ls -lh app.log
head -n 3 app.logIf your disk is short of space, pass a smaller size such as node make-log.mjs 600. Keep it above 512 MB so the next step behaves as described.
Check it worked
The script prints something like wrote app.log: 14209000 lines, 284180 errors, ls shows a file of about 1.0G, and the first line of the file is an ERROR line for user Ngozi.
Step 2 · See why readFile breaks on a big file
Create naive.mjs. It tries the obvious approach twice: once reading the file as text, once as raw bytes:
cat > naive.mjs <<'JS'
import { constants } from 'node:buffer';
import { readFile } from 'node:fs/promises';
const mb = (bytes) => Math.round(bytes / 1024 / 1024);
console.log(`longest string allowed: ${mb(constants.MAX_STRING_LENGTH)} Mi characters`);
try {
const text = await readFile('app.log', 'utf8');
console.log('as text: read', text.length, 'characters');
} catch (err) {
console.log(`as text: ${err.name}: ${err.message}`);
}
const bytes = await readFile('app.log');
console.log(`as bytes: ${mb(bytes.length)} MB in one Buffer`);
console.log(`memory in use: ${mb(process.memoryUsage().rss)} MB`);
JS
node naive.mjsReading as text fails because the JavaScript engine has a hard limit on string length, about 512 million characters, and the file is twice that. Reading as bytes works, but the process now holds the whole file in memory. On a server with 1 GB of RAM, a job like this gets killed by the operating system or pushes everything else into swap.
Check it worked
The text attempt prints an error such as RangeError: Invalid string length or Cannot create a string longer than .... The byte attempt prints as bytes: 1024 MB, and memory in use is over 1,000 MB.
Step 3 · Read the file line by line with readline
A read stream gives you chunks, but chunks do not line up with lines. The readline module does the splitting for you and works as an async iterator, so a for await loop gets one line per turn.
First create a small helper that records the highest memory use while a script runs. The next scripts import it:
cat > memory.mjs <<'JS'
// Samples resident memory every 50 ms and remembers the highest value.
export function trackPeakMemory() {
let peak = process.memoryUsage().rss;
const timer = setInterval(() => {
peak = Math.max(peak, process.memoryUsage().rss);
}, 50);
timer.unref();
return () => {
clearInterval(timer);
peak = Math.max(peak, process.memoryUsage().rss);
return Math.round(peak / 1024 / 1024);
};
}
JSrss (resident set size) is the memory the operating system has given the process, including buffers outside the JavaScript heap. timer.unref() stops the timer from keeping the program alive on its own.
Now count.mjs counts every line and every error:
cat > count.mjs <<'JS'
import { createReadStream } from 'node:fs';
import { createInterface } from 'node:readline';
import { trackPeakMemory } from './memory.mjs';
const peakMb = trackPeakMemory();
const started = performance.now();
const input = createReadStream(process.argv[2] ?? 'app.log', { encoding: 'utf8' });
const lines = createInterface({ input, crlfDelay: Infinity });
let total = 0;
let errors = 0;
for await (const line of lines) {
total++;
if (line.includes(' ERROR ')) errors++;
}
const seconds = ((performance.now() - started) / 1000).toFixed(1);
console.log(`${total} lines, ${errors} errors in ${seconds} s`);
console.log(`peak memory: ${peakMb()} MB`);
JS
node count.mjs{ encoding: 'utf8' } makes the stream decode bytes into text before it hands them on. That matters for names like Adé: é takes two bytes in UTF-8, and a 64 KiB chunk can end between them. The decoder holds back half a character until the next chunk completes it. crlfDelay: Infinity treats a Windows \r\n line ending as one line break, so files exported from Windows tools count correctly.
Check it worked
The line and error counts match what make-log.mjs printed, and peak memory is around 100 MB, a tenth of what the byte read needed. The run takes a few seconds, because the work is reading and splitting a gigabyte of text.
Step 4 · Keep only the error lines with a Transform
readline is good for reading, but to pass data on to another stream you need a stream in the middle. A Transform stream is both writable and readable: chunks go in, you decide what comes out.
Create keep-errors.mjs:
cat > keep-errors.mjs <<'JS'
import { Transform } from 'node:stream';
// Passes on only the lines that contain " ERROR ".
// A chunk can end halfway through a line, so the unfinished
// part waits in `tail` until the next chunk arrives.
export function keepErrorLines() {
let tail = '';
return new Transform({
decodeStrings: false,
transform(chunk, _encoding, callback) {
const lines = (tail + chunk).split('\n');
tail = lines.pop();
const kept = lines.filter((line) => line.includes(' ERROR '));
callback(null, kept.length > 0 ? kept.join('\n') + '\n' : undefined);
},
flush(callback) {
callback(null, tail.includes(' ERROR ') ? tail + '\n' : undefined);
},
});
}
JSHow it works:
transform()runs once per incoming chunk. The last piece aftersplit('\n')may be half a line, so it goes intotailand is joined to the front of the next chunk.- Calling
callback(null, data)sendsdatadownstream and asks for the next chunk. Passingundefined(ornull) sends nothing for that chunk. Ending the stream is done withthis.push(null), which you never need to call here. flush()runs once after the last chunk, for a final line with no newline at the end.decodeStrings: falsekeeps the incoming chunks as strings, so the UTF-8 decoding from the read stream is not undone.
Check it worked
Run the Transform on a small sample, three lines with one error split across two writes:
node --input-type=module -e "
import { keepErrorLines } from './keep-errors.mjs';
const t = keepErrorLines();
t.on('data', (d) => process.stdout.write(d));
t.write('a INFO ok\nb ERR');
t.end('OR broke\nc INFO ok');
"It prints exactly one line, b ERROR broke, even though the word ERROR arrived in two pieces.
Step 5 · Filter, gzip and write with pipeline
Now connect four streams: read the log, keep the errors, compress with gzip, write the result. pipeline from node:stream/promises joins them, handles backpressure between each pair, and returns a promise. If any stream fails, it destroys all of them and the promise rejects, so one try and catch handles every error and you are not left with open file handles.
Create filter-errors.mjs:
cat > filter-errors.mjs <<'JS'
import { createReadStream, createWriteStream } from 'node:fs';
import { rm } from 'node:fs/promises';
import { pipeline } from 'node:stream/promises';
import { createGzip } from 'node:zlib';
import { keepErrorLines } from './keep-errors.mjs';
import { trackPeakMemory } from './memory.mjs';
const [input = 'app.log', output = 'errors.log.gz'] = process.argv.slice(2);
const peakMb = trackPeakMemory();
const started = performance.now();
try {
await pipeline(
createReadStream(input, { encoding: 'utf8' }),
keepErrorLines(),
createGzip(),
createWriteStream(output),
);
const seconds = ((performance.now() - started) / 1000).toFixed(1);
console.log(`wrote ${output} in ${seconds} s`);
} catch (err) {
await rm(output, { force: true });
console.error(`failed: ${err.code ?? err.message}; removed ${output}`);
process.exitCode = 1;
} finally {
console.log(`peak memory: ${peakMb()} MB`);
}
JS
node filter-errors.mjs
ls -lh errors.log.gzThen read the result back with the standard gzip tool, which works the same on Linux and macOS:
gzip -dc errors.log.gz | wc -l
gzip -dc errors.log.gz | sed -n '1,3p'The catch block removes a half-written output file, because a truncated .gz that looks complete is worse than no file. Setting process.exitCode instead of calling process.exit() lets the finally block and any open streams finish first. Prove the error path works by pointing the script at a file that does not exist:
node filter-errors.mjs missing.log broken.gz || echo "exit code $?"
ls broken.gz 2>/dev/null || echo "no broken.gz left behind"Check it worked
The first run prints wrote errors.log.gz and a peak memory well under 200 MB. The gzipped file is under a megabyte, because repetitive log text compresses very well. wc -l prints the same error count that count.mjs found, and the lines shown include user=Adé with the accent intact. The second run prints failed: ENOENT; removed broken.gz, exit code 1 and no broken.gz left behind.
Step 6 · Watch backpressure with a slow writable
Memory stays flat because of backpressure: when the writer falls behind, the reader is told to wait. Every writable stream has a highWaterMark, the amount it buffers before it says "stop". You can watch this happen with a deliberately slow destination.
Create slow.mjs. A generator produces twelve items; a writable takes 100 ms per item and buffers at most two:
cat > slow.mjs <<'JS'
import { Readable, Writable } from 'node:stream';
import { pipeline } from 'node:stream/promises';
let made = 0;
let written = 0;
let mostWaiting = 0;
async function* items() {
for (let i = 1; i <= 12; i++) {
made = i;
mostWaiting = Math.max(mostWaiting, made - written);
console.log(`made ${i}`);
yield `item ${i}`;
}
}
const slowDisk = new Writable({
objectMode: true,
highWaterMark: 2,
write(chunk, _encoding, callback) {
setTimeout(() => {
written++;
console.log(` wrote ${chunk}`);
callback();
}, 100);
},
});
await pipeline(Readable.from(items(), { highWaterMark: 1 }), slowDisk);
console.log(`most items waiting at once: ${mostWaiting}`);
JS
node slow.mjsobjectMode: true counts the buffer in items, not bytes, which makes the numbers easy to read. The generator pauses at yield until the pipeline wants another item, so it never races ahead.
To see what backpressure protects you from, write to a stream by hand. write() returns false once the buffer is full. Code that ignores that keeps piling data into memory; code that waits for the 'drain' event does not:
cat > ignore.mjs <<'JS'
import { once } from 'node:events';
import { Writable } from 'node:stream';
function slowDisk() {
return new Writable({
objectMode: true,
highWaterMark: 2,
write(_chunk, _encoding, callback) {
setTimeout(callback, 10);
},
});
}
// 1. Ignore what write() returns: everything piles up in memory.
const careless = slowDisk();
for (let i = 1; i <= 1000; i++) careless.write(`item ${i}`);
console.log(`careless: ${careless.writableLength} items queued`);
careless.destroy();
// 2. Wait for 'drain' whenever write() returns false.
const careful = slowDisk();
let mostQueued = 0;
for (let i = 1; i <= 50; i++) {
const ok = careful.write(`item ${i}`);
mostQueued = Math.max(mostQueued, careful.writableLength);
if (!ok) await once(careful, 'drain');
}
careful.end();
console.log(`careful: never more than ${mostQueued} items queued`);
JS
node ignore.mjspipeline does the careful version for you between every pair of streams. You only need the manual write() and 'drain' pattern when you write to a stream from your own loop.
Check it worked
In the slow.mjs output the made and wrote lines interleave: the producer gets two or three items ahead, then waits, and the last line reports something like most items waiting at once: 3. The second script prints careless: 1000 items queued and careful: never more than 2 items queued.
Step 7 · Prove memory stays flat as the file grows
A streaming job should use about the same memory for a small file as for a big one. Make a 100 MB log and run the same filter on both:
node make-log.mjs 100 small.log
node filter-errors.mjs small.log small-errors.log.gz
node filter-errors.mjs app.log errors.log.gzThe 1 GB input is ten times the size of the small one, yet both runs need a fraction of what readFile needed in the second step. The time grows with the file; the memory does not.
You can push this further by capping the JavaScript heap at 64 MB. The streaming job still finishes, because it never holds more than a few chunks at once:
node --max-old-space-size=64 filter-errors.mjs app.log errors.log.gzCheck it worked
All three runs report a peak memory in the same range, well under 200 MB, compared with over 1,000 MB for the byte read in the second step. Small differences between runs come from when the garbage collector happens to run.
Step 8 · Clean up
Remove the demo folder and its two log files. This frees about 1.2 GB of disk. Node.js stays installed:
cd ~
rm -rf ~/streams-demoCheck it worked
ls ~/streams-demo reports that the folder does not exist.
Next steps
- When the work on each chunk is heavy computation rather than reading and writing, move it off the main thread: run CPU-heavy work in Node.js with worker threads.
- Brush up on the async model that
for awaitandpipelinerely on: wait for slow work with promises and async/await. - Set up Node.js 26 on a server to run jobs like this one: install Node.js 26 LTS on Ubuntu.
Related tutorials
- Write safer PHP with strict types, enums and readonly classesYou will take a loosely typed PHP 8.5 order script that gets totals quietly wrong and turn it into a typed domain model with strict types, a backed enum, readonly value objects and match, then prove it with a clean PHPStan 2.3 run.
- Write reusable TypeScript with genericsYou will replace three copy-pasted lookup functions with one generic function, then build a type-safe pluck, a Result type, a hand-written mapped type and a tested fetchJson helper in TypeScript 7.
- Write regular expressions you can read and testYou will build a small, tested Python module that pulls dates, money amounts and Nigerian and Kenyan phone numbers out of messy SMS text, and know how to port its patterns to JavaScript and when to stop using a regex.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials