CSV Parse Streaming Transform Pipeline
Parse CSV as a stream with csv-parse, validate each row against a schema, and pipe valid records onward while collecting row-level errors.
Code
import { parse } from 'csv-parse';
import { transform } from 'stream-transform';
import { createReadStream } from 'node:fs';
import { pipeline } from 'node:stream/promises';
const errors = [];
let validCount = 0;
const parser = parse({
columns: true,
skip_empty_lines: true,
trim: true,
cast: true,
bom: true,
});
const validator = transform((row, callback) => {
const issues = [];
if (!row.email || !String(row.email).includes('@')) issues.push('bad email');
if (!(row.age >= 0 && row.age <= 130)) issues.push('age out of range');
if (issues.length > 0) {
errors.push({ row: row.email ?? 'unknown', issues });
return callback(null);
}
validCount += 1;
callback(null, { email: String(row.email).toLowerCase(), age: row.age });
});
await pipeline(
createReadStream('subscribers.csv', 'utf8'),
parser,
validator,
async function* sink(records) {
for await (const record of records) {
console.log('upserting', record.email);
}
},
);
console.log('valid:', validCount, 'rejected:', errors.length);How it works
Repetition is confined to for await (const record of records) — the rest of the file is straight-line. The asynchronous flow is linearized with await, keeping failure handling local. parse, transform, createReadStream, pipeline are the only symbols borrowed from csv-parse — the coupling is explicit and narrow.
The demo data lives in module-level bindings: errors, validCount, parser, validator.
Watch out for
- External dependency:
csv-parseandstream-transform— install them before running the snippet.
Using it
Running the file prints labeled results such as upserting, valid: — each operation’s effect is visible in the output.
Key statements
errors.push({ row: row.email ?? 'unknown', issues });
for await (const record of records) {
console.log('upserting', record.email);
}
return callback(null);
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
FAQ
- Are there third-party dependencies?
- `csv-parse` and `stream-transform` — install them with the package manager before running.
Report a problem with this exampleOpens a pre-filled issue on GitHub.