typescriptintermediate
CSV Parse with Streaming
Parse large CSV files using Node.js streams with row-by-row processing and backpressure handling.
typescriptPress ⌘/Ctrl + Shift + C to copy
import { createReadStream } from 'fs';
import { createInterface } from 'readline';
interface CsvRow {
[key: string]: string;
}
export async function* parseCsv(filePath: string): AsyncGenerator<CsvRow> {
const stream = createReadStream(filePath, { encoding: 'utf-8' });
const rl = createInterface({ input: stream, crlfDelay: Infinity });
let headers: string[] = [];
let isFirst = true;
for await (const line of rl) {
if (isFirst) {
headers = line.split(',').map((h) => h.trim().replace(/^"|"$/g, ''));
isFirst = false;
continue;
}
const values = line.split(',').map((v) => v.trim().replace(/^"|"$/g, ''));
const row: CsvRow = {};
headers.forEach((h, i) => (row[h] = values[i] ?? ''));
yield row;
}
}
// Usage:
// for await (const row of parseCsv('data.csv')) {
// console.log(row);
// }Use Cases
- Data import pipelines
- ETL processing
- Log file analysis
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
pythonbeginner
Python CSV Processing Examples
Read, write, and transform CSV files using the csv module and pandas with encoding and dialect handling.
Best for: Reading and cleaning CSV data files
#csv#python
javabeginner
CSV Parser — Read and Write CSV Files
Parse and write CSV files in Java without external libraries using BufferedReader and String operations.
Best for: Parsing CSV data files without external libraries
#java#csv
typescriptadvanced
Stream File Download
Express handler that streams a file to the client with proper headers, range support, and error handling.
Best for: Large file downloads
#stream#download
typescriptbeginner
URL and Query String Parsing
Parse, construct, and manipulate URLs and query strings using the Node.js URL and URLSearchParams API.
Best for: API URL construction
#nodejs#url