Snowcone field notes 03 / 03
Read a file line by line in Node.js with Snowcone
To process a text file incrementally in Node.js, use Snowcone’s readLines(path) with for await...of. It yields line strings without calling readFile() to load the entire file. Version 0.2.0 wraps Node’s FileHandle.readLines() and closes the file in a finally block.
Package note: This guide describes version 0.2.0 and includes native alternatives where they are useful.
Install and count matching log lines
Use Node.js 20 or later and ECMAScript modules. Save the examples as .mjs files, or set "type": "module" in your project’s package.json.
npm install [email protected]Pinning the version makes these examples reproducible. Check npm for newer releases and compare their API before upgrading.
Create app.log with this sample text:
INFO server started
ERROR database unavailable
INFO retrying
ERROR request failedSave this as count-errors.mjs, then run node count-errors.mjs from the directory containing app.log.
import { readLines } from "snowcone";
let errorCount = 0;
try {
for await (const line of readLines("./app.log")) {
if (line.includes("ERROR")) errorCount++;
}
console.log(`ERROR lines: ${errorCount}`);
} catch (error) {
console.error("Could not read app.log:", error.message);
process.exitCode = 1;
}The result is ERROR lines: 2. The example counts matching lines, not individual occurrences within a line. Errors from opening or reading the file are handled around the entire loop.
What incremental reading saves—and what it does not
Reading a file with readFile() and splitting it creates a full-file value plus the representation of its lines. readLines() instead consumes a stream and yields lines as you iterate. For a large log, that avoids intentionally retaining the entire file.
This does not mean exactly one line exists in memory, or that memory use is a fixed constant. Node buffers stream data, a very long line can itself be large, and anything your application stores adds to the total. Collecting every yielded line into an array gives up the main memory benefit.
Likewise, await your asynchronous processing inside the loop when you want sequential work. Starting a promise for every line and keeping them all can accumulate an unbounded backlog, even though file reading is incremental.
Stop early and close the file
If you only need the first match, break out of the loop:
import { readLines } from "snowcone";
for await (const line of readLines("./app.log")) {
if (line.includes("ERROR")) {
console.log(line);
break;
}
}A normal break from for await...of closes the async generator. Snowcone’s finally block then closes its file handle. That cleanup also runs when the generator finishes normally or the loop exits through a thrown error. Abruptly terminating the process is a different situation.
Process lines in batches
Snowcone 0.2.0 yields one line per iteration. It does not expose a batch-size argument. The following is an application-level wrapper, not another built-in Snowcone API:
import { readLines } from "snowcone";
async function* batchLines(path, batchSize = 500) {
if (!Number.isInteger(batchSize) || batchSize < 1) {
throw new RangeError("batchSize must be a positive integer");
}
let batch = [];
for await (const line of readLines(path)) {
batch.push(line);
if (batch.length === batchSize) {
yield batch;
batch = [];
}
}
if (batch.length > 0) yield batch;
}
for await (const batch of batchLines("./app.log", 500)) {
// Replace this with your own processing or database write.
console.log(`Processing ${batch.length} lines`);
}The final partial batch is yielded too. Memory retained by this wrapper scales with the text in one batch, plus the underlying reader’s buffers. If lines vary greatly in length, a line-count limit is not a byte limit. Await your own database or network work before continuing to avoid piling up batches.
The native Node.js alternative
You can use Node’s file API directly. This is essentially the lifecycle that Snowcone packages into its async generator:
import { open } from "node:fs/promises";
const file = await open("./app.log", "r");
try {
for await (const line of file.readLines({ autoClose: false })) {
console.log(line);
}
} finally {
await file.close();
}Use the native API if you need its full options or prefer no extra dependency. Use Snowcone when you want the short readLines(path) interface and explicit cleanup bundled with your other utilities.
API boundaries and formats
| Question | Snowcone 0.2.0 behavior |
|---|---|
| Input | A path accepted by Node’s open(), such as "./app.log". |
| Output | An async generator yielding text lines without their line terminators. |
| Runtime | Node.js 20 or later; ESM examples. Not a browser file API. |
| Options | No exposed encoding, buffer-size, start-offset, or batch-size options. |
| Missing file | Opening rejects during iteration; catch around for await. |
| CSV | Text lines only. CSV records with quoted newlines require a CSV-aware parser. |
For JSON Lines, parse each line with JSON.parse() and decide how to handle blank or invalid lines. For a single large JSON array, line iteration alone is not a streaming JSON parser. Choose a format-aware parser when record boundaries differ from line boundaries.
Common questions
Does readLines load the entire file?
It uses Node’s line reader rather than whole-file readFile(). Internal buffering and the length of individual lines still affect memory.
Can it read CSV in batches?
The wrapper above batches text lines, not parsed CSV records. Use a streaming CSV parser for general CSV, especially fields containing newlines.
Does it work in a browser?
No. It opens files through node:fs/promises and requires Node.js.
Sources and version
Examples were checked against the published [email protected] package. Implementation details refer to the linked source snapshot, not a promise about future versions.