readLines(): stream a file with readline
TypeScript
import { createReadStream } from 'node:fs';
import { createInterface } from 'node:readline';
/** Stream a text file lazily; huge logs never load into memory at once. */
export async function* readLines(path: string): AsyncGenerator<string, void, void> {
const stream = createReadStream(path, { encoding: 'utf8' });
const lines = createInterface({ input: stream, crlfDelay: Infinity });
try {
for await (const line of lines) yield line;
} finally {
lines.close();
stream.destroy();
}
}
/** Read only the first `limit` lines, closing the stream early. */
export async function readFirstLines(path: string, limit = 20): Promise<string[]> {
const selected: string[] = [];
if (limit <= 0) return selected;
for await (const line of readLines(path)) {
selected.push(line);
if (selected.length >= limit) break;
}
return selected;
}
// for await (const line of readLines('./access.log')) console.log(line);