From: Ardis Lu Date: Thu, 9 Jan 2025 05:44:24 +0000 (-0800) Subject: Add example for returning null in transformation X-Git-Tag: v0.1.0~136 X-Git-Url: https://git.ardis.lu/?a=commitdiff_plain;h=bc1099b05940a9456c570b070acbc28d0be1e67a;p=csvio Add example for returning null in transformation --- diff --git a/examples/data/ex5-in.csv b/examples/data/ex5-in.csv new file mode 100644 index 0000000..9042246 --- /dev/null +++ b/examples/data/ex5-in.csv @@ -0,0 +1,10 @@ +ABC System Report +ID# XXX-123 +2025-01-08 +,, +,, +Name,Value_1,Value_2 +A,1111,11 +B,2222,22 +C,3333,33 +D,4444,44 diff --git a/examples/data/ex5-out.csv b/examples/data/ex5-out.csv new file mode 100644 index 0000000..a874060 --- /dev/null +++ b/examples/data/ex5-out.csv @@ -0,0 +1,5 @@ +Report,ID,Date,Name,Value_1,Value_2 +ABC System Report,XXX-123,2025-01-08,A,1111,11 +ABC System Report,XXX-123,2025-01-08,B,2222,22 +ABC System Report,XXX-123,2025-01-08,C,3333,33 +ABC System Report,XXX-123,2025-01-08,D,4444,44 diff --git a/examples/ex5.js b/examples/ex5.js new file mode 100644 index 0000000..e08db19 --- /dev/null +++ b/examples/ex5.js @@ -0,0 +1,29 @@ +// ## Example 5: Handling an irregularly-shaped CSV file +// +// `createCSVReadableStream` can parse CSVs that have rows with a mismatching number of columns, for example CSVs +// with informational file headers. This information can be handled as required in the transformation function. +// +// Return `null` in the transformation function to consume an input row without emitting an output row. + +import { createCSVReadableStream, createCSVTransformStream, createCSVWritableStream } from '../src/index.js'; + +let i = 0; +let report, id, date; +function parse(row) { + // Special logic for the first six rows of the CSV + switch (i++) { + case 0: report = row[0]; return null; + case 1: id = row[0].split(' ')[1]; return null; + case 2: date = row[0]; return null; + case 3: return null; + case 4: return null; + case 5: return ['Report', 'ID', 'Date', 'Name', 'Value_1', 'Value_2']; + } + + // Normal logic for the rest of the CSV + return [report, id, date, ...row]; +} + +createCSVReadableStream('./data/ex5-in.csv') + .pipeThrough(createCSVTransformStream(parse, { includeHeaders: true })) + .pipeTo(createCSVWritableStream('./data/ex5-out.csv')); \ No newline at end of file