CSV Stream Transform With Headers

Parse and transform CSV streams with header mapping type coercion and column selection for data pipelines.

JavascriptData Fetching

Code

javascriptsnippet
1 line
import{Transform}from'node:stream';export function csvTransform({headers,delimiter=',',select}={}){let firstLine=true;let headerMap=[];return new Transform({objectMode:true,transform(chunk,_,cb){const lines=chunk.toString().split('\n');const result=[];for(let line of lines){if(!line.trim())continue;const cols=line.split(delimiter);if(firstLine){headerMap=headers??cols;firstLine=false;continue;}const obj={};for(let i=0;i<headerMap.length;i++)obj[headerMap[i]]=cols[i];if(select){const filtered={};for(const k of select)filtered[k]=obj[k];result.push(filtered);}else result.push(obj);}this.push(result);cb();}});}

How the snippet works

Count the function csvTransform as the entire surface area of CSV Stream Transform With Headers.

The import names the platform contact area: Transform, all from node:stream.

The return value is newly constructed — inputs are never handed back.

Points of care

  • The dependency surface is just node:stream, and that one is built into Node.js.

Applying it

Signature: export function csvTransform({headers,delimiter=',',select}={})

The surface worth importing is csvTransform; the helpers around it are private to the snippet.

Interactive Tools for This Topic

FAQ

Does `csvTransform` modify its input?
No — a new value is constructed for the result and the arguments are never written to.
Does this require external packages?
No — `node:stream` is a Node.js built-in module; nothing to install.