Read a JSON Lines file line by line

JavaScript
// Stream a .jsonl file and process one parsed record at a time.
const fs = require('node:fs');
const readline = require('node:readline');

async function* readJsonLines(path) {
  const stream = fs.createReadStream(path, { encoding: 'utf8' });
  const lines = readline.createInterface({ input: stream, crlfDelay: Infinity });
  let lineNumber = 0;
  for await (const line of lines) {
    lineNumber += 1;
    const trimmed = line.trim();
    if (!trimmed) continue;
    let record;
    try {
      record = JSON.parse(trimmed);
    } catch (error) {
      throw new Error(`invalid JSON on line ${lineNumber}: ${error.message}`);
    }
    yield record;
  }
}

(async () => {
  let total = 0;
  for await (const event of readJsonLines('events.jsonl')) {
    if (event.type === 'purchase') total += event.amount ?? 0;
  }
  console.log('revenue:', total.toFixed(2));
})();