[Example 1.1: Basic usage](./ex1_1.js)
-[Example 1.2: Updating headers in the output](./ex1_2.js)
+[Example 1.2: Replace headers in the output](./ex1_2.js)
[Example 1.3: Chaining multiple transformations](./ex1_3.js)
-// ## Example 1.2: Updating headers in the output
+// ## Example 1.2: Replace headers in the output
//
-// Set `handleHeaders: true` to manually handle the header row (first row).
+// Set `handleHeaders` to an `Array<any>` to replace the header row (first row) in the output.
//
// Notes:
// - The header row is assumed to be the first row in the input CSV, and by default it goes directly to the output (skipping the user-provided transformation function).
-// - If your input CSV does not have a header row, set `handleHeaders: true` and process the header row (first row) normally.
-// - Otherwise, you will need distinct logic to handle the header row vs. data rows. A simple boolean variable is a good way to switch between this logic.
+// - Setting `handleHeaders` to an array is the simplest way to rename headers, delete headers, or add new headers.
import { CSVReader, CSVTransformer, CSVWriter } from '../src/index.js';
-let firstRow = true;
function sum(row) {
- if (firstRow) {
- firstRow = false;
- return [...row, 'sum'];
- }
return [...row, Number(row[0]) + Number(row[1])];
}
await new CSVReader(new URL('./data/ex1_2-in.csv', import.meta.url))
- .pipeThrough(new CSVTransformer(sum, { handleHeaders: true }))
+ .pipeThrough(new CSVTransformer(sum, { handleHeaders: ['Column A', 'Column B', 'Sum'] }))
.pipeTo(new CSVWriter(new URL('./data/ex1_2-out.csv', import.meta.url)));
\ No newline at end of file
// (`rawOutput`) when handling the transformation function input/output. These options are intended for advanced
// transformations (e.g., transformations spread across multiple functions or lower-level transformations directly
// on byte arrays).
+//
+// Set `handleHeaders` to `true` to pass the header row to the transformation function as a normal row and manually
+// handle the header output processing. This setting is required if the input CSV does not have a header row.
import { CSVReader, CSVTransformer, CSVWriter } from '../src/index.js';
return Math.floor(ms / 100);
}
-let firstChunk = true;
async function concurrent(row) {
- if (firstChunk) {
- firstChunk = false;
- return ['tick number', ...row];
- }
await setTimeout(100); // Simulate some slow task, e.g. a network request
return [tick(), ...row];
}
await new CSVReader(new URL('./data/ex3_2-in.csv', import.meta.url))
- .pipeThrough(new CSVTransformer(concurrent, { handleHeaders: true, maxConcurrent: 5 }))
+ .pipeThrough(new CSVTransformer(concurrent, { handleHeaders: h => ['tick number', ...h], maxConcurrent: 5 }))
.pipeTo(new CSVWriter(new URL('./data/ex3_2-out.csv', import.meta.url)));
\ No newline at end of file