### Format CSV Data with Headers (TypeScript/JavaScript) Source: https://c2fo.github.io/fast-csv/docs/introduction/example This example demonstrates how to format CSV data with headers using fast-csv. It pipes the formatted output to process.stdout. Dependencies include the 'fast-csv' library. ```typescript import * as csv from 'fast-csv'; const csvStream = csv.format({ headers: true });csvStream.pipe(process.stdout).on('end', () => process.exit());csvStream.write({ header1: 'row1-col1', header2: 'row1-col2' });csvStream.write({ header1: 'row2-col1', header2: 'row2-col2' });csvStream.write({ header1: 'row3-col1', header2: 'row3-col2' });csvStream.write({ header1: 'row4-col1', header2: 'row4-col2' });csvStream.write({ header1: 'row5-col1', header2: 'row5-col2' });csvStream.end(); ``` -------------------------------- ### Parse and Format CSV with Transformation (TypeScript/JavaScript) Source: https://c2fo.github.io/fast-csv/docs/introduction/example This advanced example demonstrates parsing a CSV file, transforming the data (mapping snake_case to camelCase and fetching user details), and then formatting it into a new CSV output. Dependencies include 'fs', 'path', 'fast-csv', and a User model. Note the use of a transform function for custom data manipulation. ```typescript import * as fs from 'fs'; import * as path from 'path'; import * as csv from 'fast-csv'; import { User } from './models/user'; interface UserCsvRow { id: string; first_name: string; last_name: string; address: string; } interface UserDetailsRow { id: number; firstName: string; lastName: string; address: string; // properties from user isVerified: boolean; hasLoggedIn: boolean; age: number; } fs.createReadStream(path.resolve(__dirname, 'assets', 'snake_case_users.csv')) .pipe(csv.parse({ headers: true })) // pipe the parsed input into a csv formatter .pipe( csv.format({ headers: true }), ) // Using the transform function from the formatting stream .transform((row, next): void => { User.findById(+row.id, (err, user) => { if (err) { return next(err); } if (!user) { return next(new Error(`Unable to find user for ${row.id}`)); } return next(null, { id: user.id, firstName: row.first_name, lastName: row.last_name, address: row.address, // properties from user isVerified: user.isVerified, hasLoggedIn: user.hasLoggedIn, age: user.age, }); }); }) .pipe(process.stdout) .on('end', () => process.exit()); ``` -------------------------------- ### Parse CSV File with Headers (TypeScript/JavaScript) Source: https://c2fo.github.io/fast-csv/docs/introduction/example This example shows how to parse a CSV file with headers using fast-csv. It reads a CSV file, parses its content, and logs each row to the console. Dependencies include 'fs', 'path', and 'fast-csv'. ```typescript import * as fs from 'fs'; import * as path from 'path'; import * as csv from 'fast-csv'; fs.createReadStream(path.resolve(__dirname, 'assets', 'parse.csv')) .pipe(csv.parse({ headers: true })) .on('error', error => console.error(error)) .on('data', row => console.log(row)) .on('end', (rowCount: number) => console.log(`Parsed ${rowCount} rows`)); ``` -------------------------------- ### Skip Initial Lines with skipLines in Fast-CSV Source: https://c2fo.github.io/fast-csv/docs/parsing/examples Shows how to skip a specified number of initial lines from the CSV input using the `skipLines` option. This option is applied before header detection, meaning the header row itself might be one of the skipped lines. The example processes CSV data, skipping the initial lines and then parsing the rest. ```typescript import { parse } from '@fast-csv/parse'; const rows = [ 'skip1_header1,skip1_header2\n', 'skip2_header1,skip2_header2\n', 'header1,header2\n', 'col1,col1\n', 'col2,col2\n', 'col3,col3\n', 'col4,col4\n', ]; const stream = parse({ headers: true, skipLines: 2 }) .on('error', error => console.error(error)) .on('data', row => console.log(row)) .on('end', (rowCount: number) => console.log(`Parsed ${rowCount} rows`)); rows.forEach(row => stream.write(row)); stream.end(); ``` ```javascript import { parse } from '@fast-csv/parse'; const rows = [ 'skip1_header1,skip1_header2\n', 'skip2_header1,skip2_header2\n', 'header1,header2\n', 'col1,col1\n', 'col2,col2\n', 'col3,col3\n', 'col4,col4\n', ]; const stream = parse({ headers: true, skipLines: 2 }) .on('error', error => console.error(error)) .on('data', row => console.log(row)) .on('end', (rowCount) => console.log(`Parsed ${rowCount} rows`)); rows.forEach(row => stream.write(row)); stream.end(); ``` -------------------------------- ### Provide Custom Headers for Array Rows in Fast-CSV Source: https://c2fo.github.io/fast-csv/docs/formatting/examples Demonstrates how to provide a custom set of headers when working with array rows. This allows for explicit control over column names and order in the output CSV. ```typescript import { format } from '@fast-csv/format'; const csvStream = format({ headers: ['header1', 'header2'] });csvStream.pipe(process.stdout).on('end', () => process.exit());csvStream.write(['value1a', 'value1b']);csvStream.write(['value2a', 'value2b']);csvStream.write(['value3a', 'value3b']);csvStream.write(['value4a', 'value4b']);csvStream.end(); ``` ```javascript const { format } = require('@fast-csv/format'); const csvStream = format({ headers: ['header1', 'header2'] });csvStream.pipe(process.stdout).on('end', () => process.exit());csvStream.write(['value1a', 'value1b']);csvStream.write(['value2a', 'value2b']);csvStream.write(['value3a', 'value3b']);csvStream.write(['value4a', 'value4b']);csvStream.end(); ``` -------------------------------- ### Limit Parsed Rows with maxRows in Fast-CSV Source: https://c2fo.github.io/fast-csv/docs/parsing/examples Demonstrates how to limit the number of rows parsed from a CSV stream using the `maxRows` option. This is useful for processing only a subset of large CSV files. The example expects CSV data as input and outputs parsed rows up to the specified limit. ```typescript import { parse } from '@fast-csv/parse'; const rows = [ 'header1,header2\n', 'col1,col1\n', 'col2,col2\n', 'col3,col3\n', 'col4,col4\n', 'col5,col5\n', 'col6,col6\n', 'col7,col7\n', 'col8,col8\n', 'col9,col9\n', 'col10,col10', ]; const stream = parse({ headers: true, maxRows: 5 }) .on('error', error => console.error(error)) .on('data', row => console.log(row)) .on('end', (rowCount: number) => console.log(`Parsed ${rowCount} rows`)); rows.forEach(row => stream.write(row)); stream.end(); ``` ```javascript import { parse } from '@fast-csv/parse'; const rows = [ 'header1,header2\n', 'col1,col1\n', 'col2,col2\n', 'col3,col3\n', 'col4,col4\n', 'col5,col5\n', 'col6,col6\n', 'col7,col7\n', 'col8,col8\n', 'col9,col9\n', 'col10,col10', ]; const stream = parse({ headers: true, maxRows: 5 }) .on('error', error => console.error(error)) .on('data', row => console.log(row)) .on('end', (rowCount) => console.log(`Parsed ${rowCount} rows`)); rows.forEach(row => stream.write(row)); stream.end(); ``` -------------------------------- ### Skip Data Rows with skipRows in Fast-CSV Source: https://c2fo.github.io/fast-csv/docs/parsing/examples Illustrates how to skip a specified number of data rows from the beginning of a CSV input using the `skipRows` option. This option affects only the data rows after the header. The example takes CSV data and outputs rows, excluding the skipped ones. ```typescript import { parse } from '@fast-csv/parse'; const rows = [ 'header1,header2\n', 'col1,col1\n', 'col2,col2\n', 'col3,col3\n', 'col4,col4\n', 'col5,col5\n', 'col6,col6\n', ]; const stream = parse({ headers: true, skipRows: 2 }) .on('error', error => console.error(error)) .on('data', row => console.log(row)) .on('end', (rowCount: number) => console.log(`Parsed ${rowCount} rows`)); rows.forEach(row => stream.write(row)); stream.end(); ``` ```javascript import { parse } from '@fast-csv/parse'; const rows = [ 'header1,header2\n', 'col1,col1\n', 'col2,col2\n', 'col3,col3\n', 'col4,col4\n', 'col5,col5\n', 'col6,col6\n', ]; const stream = parse({ headers: true, skipRows: 2 }) .on('error', error => console.error(error)) .on('data', row => console.log(row)) .on('end', (rowCount) => console.log(`Parsed ${rowCount} rows`)); rows.forEach(row => stream.write(row)); stream.end(); ``` -------------------------------- ### Manual CSV Write using fast-csv Source: https://c2fo.github.io/fast-csv/docs/parsing/examples Demonstrates how to manually write CSV data using the fast-csv library. It configures the parser with headers enabled and handles data, errors, and the end of the stream. Input is provided via stream.write. ```typescript import { parse } from '@fast-csv/parse'; const stream = parse({ headers: true }) .on('error', error => console.error(error)) .on('data', row => console.log(row)) .on('end', (rowCount: number) => console.log(`Parsed ${rowCount} rows`)); stream.write('header1,header2\n'); stream.write('col1,col2'); stream.end(); ``` ```javascript const { parse } = require('@fast-csv/parse'); const stream = parse({ headers: true }) .on('error', error => console.error(error)) .on('data', row => console.log(row)) .on('end', (rowCount) => console.log(`Parsed ${rowCount} rows`)); stream.write('header1,header2\n'); stream.write('col1,col2'); stream.end(); ``` -------------------------------- ### Reorder Columns Using Custom Headers in Fast-CSV Source: https://c2fo.github.io/fast-csv/docs/formatting/examples Illustrates how to reorder columns in the output CSV by providing a custom 'headers' array. This is particularly useful when input objects have a different order than desired in the CSV. ```typescript import { format } from '@fast-csv/format'; const csvStream = format({ headers: ['header2', 'header1'] });csvStream.pipe(process.stdout).on('end', () => process.exit());csvStream.write({ header1: 'value1a', header2: 'value1b' });csvStream.write({ header1: 'value2a', header2: 'value2b' });csvStream.write({ header1: 'value3a', header2: 'value3b' });csvStream.write({ header1: 'value4a', header2: 'value4b' });csvStream.end(); ``` ```javascript const { format } = require('@fast-csv/format'); const csvStream = format({ headers: ['header2', 'header1'] });csvStream.pipe(process.stdout).on('end', () => process.exit());csvStream.write({ header1: 'value1a', header2: 'value1b' });csvStream.write({ header1: 'value2a', header2: 'value2b' });csvStream.write({ header1: 'value3a', header2: 'value3b' });csvStream.write({ header1: 'value4a', header2: 'value4b' });csvStream.end(); ``` -------------------------------- ### Auto-Discover Headers from Hash Arrays using TypeScript and JavaScript Source: https://c2fo.github.io/fast-csv/docs/formatting/examples Demonstrates how fast-csv automatically discovers headers from hash arrays when the `headers` option is set to `true`. This method is useful when rows are represented as key-value pairs. ```typescript import { format } from '@fast-csv/format'; const csvStream = format({ headers: true });csvStream.pipe(process.stdout).on('end', () => process.exit());csvStream.write([ ['header1', 'value1a'], ['header2', 'value1b'], ]);csvStream.write([ ['header1', 'value2a'], ['header2', 'value2b'], ]);csvStream.write([ ['header1', 'value3a'], ['header2', 'value3b'], ]);csvStream.write([ ['header1', 'value4a'], ['header2', 'value4b'], ]);csvStream.end(); ``` ```javascript const { format } = require('@fast-csv/format'); const csvStream = format({ headers: true });csvStream.pipe(process.stdout).on('end', () => process.exit());csvStream.write([ ['header1', 'value1a'], ['header2', 'value1b'], ]);csvStream.write([ ['header1', 'value2a'], ['header2', 'value2b'], ]);csvStream.write([ ['header1', 'value3a'], ['header2', 'value3b'], ]);csvStream.write([ ['header1', 'value4a'], ['header2', 'value4b'], ]);csvStream.end(); ``` -------------------------------- ### Quote All Columns and Headers in Fast-CSV Source: https://c2fo.github.io/fast-csv/docs/formatting/examples Shows how to enable quoting for all columns and headers by setting the `quoteColumns` option to `true`. This ensures that all data fields and header names are enclosed in quotes, adhering to specific CSV formatting requirements. ```typescript import { format } from '@fast-csv/format'; const csvStream = format({ headers: true, quoteColumns: true });csvStream.pipe(process.stdout).on('end', () => process.exit());csvStream.write({ header1: 'value1a', header2: 'value2a' });csvStream.write({ header1: 'value1a', header2: 'value2a' });csvStream.write({ header1: 'value1a', header2: 'value2a' });csvStream.write({ header1: 'value1a', header2: 'value2a' });csvStream.end(); ``` ```javascript const { format } = require('@fast-csv/format'); const csvStream = format({ headers: true, quoteColumns: true });csvStream.pipe(process.stdout).on('end', () => process.exit());csvStream.write({ header1: 'value1a', header2: 'value2a' });csvStream.write({ header1: 'value1a', header2: 'value2a' });csvStream.write({ header1: 'value1a', header2: 'value2a' });csvStream.write({ header1: 'value1a', header2: 'value2a' });csvStream.end(); ``` -------------------------------- ### Asynchronous Row Transformation in CSV (TypeScript) Source: https://c2fo.github.io/fast-csv/docs/formatting/examples Illustrates how to perform asynchronous row transformations in CSV data using a callback within the `.transform` method. This is suitable for operations that involve I/O or other asynchronous tasks. It requires the '@fast-csv/format' package. ```typescript import { format } from '@fast-csv/format'; interface CsvRow { header1: string; header2: string; } const csvStream = format({ headers: true }) .transform((row, cb) => { setImmediate(() => cb(null, { header1: row.header1.toUpperCase(), header2: row.header2.toUpperCase(), })); });csvStream.pipe(process.stdout).on('end', () => process.exit());csvStream.write({ header1: 'value1a', header2: 'value2a' });csvStream.write({ header1: 'value1a', header2: 'value2a' });csvStream.write({ header1: 'value1a', header2: 'value2a' });csvStream.write({ header1: 'value1a', header2: 'value2a' });csvStream.end(); ``` -------------------------------- ### CSV Parsing with Skipped Columns using fast-csv Source: https://c2fo.github.io/fast-csv/docs/parsing/examples Shows how to skip specific columns during CSV parsing by providing a sparse array to the `headers` option. `undefined` entries in the array indicate columns to be skipped. Handles errors and stream completion. Input is a string. ```typescript import { EOL } from 'os'; import { parse } from '@fast-csv/parse'; const CSV_STRING = [ 'a1,b1,c1', 'a2,b2,c2' ].join(EOL); const stream = parse({ headers: ['a', undefined, 'c'] }) .on('error', error => console.error(error)) .on('data', row => console.log(row)) .on('end', (rowCount: number) => console.log(`Parsed ${rowCount} rows`)); stream.write(CSV_STRING); stream.end(); ``` ```javascript const { EOL } = require('os'); const { parse } = require('@fast-csv/parse'); const CSV_STRING = [ 'a1,b1,c1', 'a2,b2,c2' ].join(EOL); const stream = parse({ headers: ['a', undefined, 'c'] }) .on('error', error => console.error(error)) .on('data', row => console.log(row)) .on('end', (rowCount) => console.log(`Parsed ${rowCount} rows`)); stream.write(CSV_STRING); stream.end(); ``` -------------------------------- ### Do Not Write Auto-Discovered Headers in Fast-CSV Source: https://c2fo.github.io/fast-csv/docs/formatting/examples Explains how to prevent the writing of auto-discovered headers in the CSV output by setting `writeHeaders` to `false`. This is useful when headers are not needed or will be added separately. ```typescript import { format } from '@fast-csv/format'; const csvStream = format({ headers: true, writeHeaders: false });csvStream.pipe(process.stdout).on('end', () => process.exit());csvStream.write({ header1: 'value1a', header2: 'value2a' });csvStream.write({ header1: 'value1a', header2: 'value2a' });csvStream.write({ header1: 'value1a', header2: 'value2a' });csvStream.write({ header1: 'value1a', header2: 'value2a' });csvStream.end(); ``` ```javascript const { format } = require('@fast-csv/format'); const csvStream = format({ headers: true, writeHeaders: false });csvStream.pipe(process.stdout).on('end', () => process.exit());csvStream.write({ header1: 'value1a', header2: 'value2a' });csvStream.write({ header1: 'value1a', header2: 'value2a' });csvStream.write({ header1: 'value1a', header2: 'value2a' });csvStream.write({ header1: 'value1a', header2: 'value2a' });csvStream.end(); ``` -------------------------------- ### Transform Rows in CSV Data Using Options (TypeScript) Source: https://c2fo.github.io/fast-csv/docs/formatting/examples Shows how to transform rows in CSV data by providing a separate transform function in the formatter options. This approach is useful for reusability and cleaner code. It requires the '@fast-csv/format' package. ```typescript import { format } from '@fast-csv/format'; interface CsvRow { header1: string; header2: string; } const transform = (row: CsvRow): CsvRow => ({ header1: row.header1.toUpperCase(), header2: row.header2.toUpperCase(), }); const csvStream = format({ headers: true, transform });csvStream.pipe(process.stdout).on('end', () => process.exit());csvStream.write({ header1: 'value1a', header2: 'value2a' });csvStream.write({ header1: 'value1a', header2: 'value2a' });csvStream.write({ header1: 'value1a', header2: 'value2a' });csvStream.write({ header1: 'value1a', header2: 'value2a' });csvStream.end(); ``` -------------------------------- ### Remove Columns Using Custom Headers in Fast-CSV Source: https://c2fo.github.io/fast-csv/docs/formatting/examples Demonstrates how to remove specific columns from the output CSV by providing a 'headers' array that only includes the desired columns. This effectively filters out unwanted data. ```typescript import { format } from '@fast-csv/format'; const csvStream = format({ headers: ['header2'] });csvStream.pipe(process.stdout).on('end', () => process.exit());csvStream.write({ header1: 'value1a', header2: 'value1b' });csvStream.write({ header1: 'value2a', header2: 'value2b' });csvStream.write({ header1: 'value3a', header2: 'value3b' });csvStream.write({ header1: 'value4a', header2: 'value4b' });csvStream.end(); ``` ```javascript const { format } = require('@fast-csv/format'); const csvStream = format({ headers: ['header2'] });csvStream.pipe(process.stdout).on('end', () => process.exit());csvStream.write({ header1: 'value1a', header2: 'value1b' });csvStream.write({ header1: 'value2a', header2: 'value2b' });csvStream.write({ header1: 'value3a', header2: 'value3b' });csvStream.write({ header1: 'value4a', header2: 'value4b' });csvStream.end(); ``` -------------------------------- ### Create and Append to CSV File (TypeScript) Source: https://c2fo.github.io/fast-csv/docs/formatting/examples Demonstrates creating a new CSV file and then appending data to it using the Fast-CSV library. It defines a `CsvFile` class to manage file operations, including writing headers and appending rows. This requires `@fast-csv/format`, `fs`, and `path` modules. ```typescript import * as path from 'path'; import * as fs from 'fs'; import { FormatterOptionsArgs, Row, writeToStream } from '@fast-csv/format'; type CsvFileOpts = { headers: string[]; path: string; }; class CsvFile { static write(stream: NodeJS.WritableStream, rows: Row[], options: FormatterOptionsArgs): Promise { return new Promise((res, rej) => { writeToStream(stream, rows, options) .on('error', (err: Error) => rej(err)) .on('finish', () => res()); }); } private readonly headers: string[]; private readonly path: string; private readonly writeOpts: FormatterOptionsArgs; constructor(opts: CsvFileOpts) { this.headers = opts.headers; this.path = opts.path; this.writeOpts = { headers: this.headers, includeEndRowDelimiter: true }; } create(rows: Row[]): Promise { return CsvFile.write(fs.createWriteStream(this.path), rows, { ...this.writeOpts }); } append(rows: Row[]): Promise { return CsvFile.write(fs.createWriteStream(this.path, { flags: 'a' }), rows, { ...this.writeOpts, // dont write the headers when appending writeHeaders: false, } as FormatterOptionsArgs); } read(): Promise { return new Promise((res, rej) => { fs.readFile(this.path, (err, contents) => { if (err) { return rej(err); } return res(contents); }); }); } } const csvFile = new CsvFile({ path: path.resolve(__dirname, 'append.tmp.csv'), // headers to write headers: ['c', 'b', 'a'], }); // 1. create the csv csvFile .create([ { a: 'a1', b: 'b1', c: 'c1' }, { b: 'b2', a: 'a2', c: 'c2' }, { a: 'a3', b: 'b3', c: 'c3' }, ]) // append rows to file .then(() => csvFile.append([ { a: 'a4', b: 'b4', c: 'c4' }, { a: 'a5', b: 'b5', c: 'c5' }, ]), ) // append another row .then(() => csvFile.append([{ a: 'a6', b: 'b6', c: 'c6' }])) .then(() => csvFile.read()) .then(contents => { console.log(`${contents}`); }) .catch(err => { console.error(err.stack); process.exit(1); }); ``` -------------------------------- ### Change CSV Quote Character using TypeScript and JavaScript Source: https://c2fo.github.io/fast-csv/docs/formatting/examples Shows how to change the default quote character from double quotes (` ```typescript import { format } from '@fast-csv/format'; const stream = format({ quote: "'" }); stream.pipe(process.stdout); // each field will be quoted because it contains a delimiter stream.write(['a,a', 'b,b']); stream.write(['a1,a1', 'b1,b1']); stream.write(['a2,a2', 'b2,b2']); stream.end(); ``` ```javascript const { format } = require('@fast-csv/format'); const stream = format({ quote: "'" }); stream.pipe(process.stdout); // each field will be quoted because it contains a delimiter stream.write(['a,a', 'b,b']); stream.write(['a1,a1', 'b1,b1']); stream.write(['a2,a2', 'b2,b2']); stream.end(); ``` -------------------------------- ### Change CSV Escape Character using TypeScript and JavaScript Source: https://c2fo.github.io/fast-csv/docs/formatting/examples Demonstrates how to change the default escape character from double quotes (` ```typescript import { format } from '@fast-csv/format'; const stream = format({ escape: "'" }); stream.pipe(process.stdout); // wrap each field in a quote so it is escaped and quoted stream.write(['"a"', '"b"']); stream.write(['"a1"', '"b1"']); stream.write(['"a2"', '"b2"']); stream.end(); ``` ```javascript const { format } = require('@fast-csv/format'); const stream = format({ escape: "'" }); stream.pipe(process.stdout); // wrap each field in a quote so it is escaped and quoted stream.write(['"a"', '"b"']); stream.write(['"a1"', '"b1"']); stream.write(['"a2"', '"b2"']); stream.end(); ``` -------------------------------- ### CSV Parsing with Custom Headers using fast-csv Source: https://c2fo.github.io/fast-csv/docs/parsing/examples Explains how to provide custom header names for CSV parsing by passing an array to the `headers` option. The order in the array must match the data columns. Handles errors and stream completion. Input is a string. ```typescript import { EOL } from 'os'; import { parse } from '@fast-csv/parse'; const CSV_STRING = [ 'a1,b1', 'a2,b2' ].join(EOL); const stream = parse({ headers: ['a', 'b'] }) .on('error', error => console.error(error)) .on('data', row => console.log(row)) .on('end', (rowCount: number) => console.log(`Parsed ${rowCount} rows`)); stream.write(CSV_STRING); stream.end(); ``` ```javascript const { EOL } = require('os'); const { parse } = require('@fast-csv/parse'); const CSV_STRING = [ 'a1,b1', 'a2,b2' ].join(EOL); const stream = parse({ headers: ['a', 'b'] }) .on('error', error => console.error(error)) .on('data', row => console.log(row)) .on('end', (rowCount) => console.log(`Parsed ${rowCount} rows`)); stream.write(CSV_STRING); stream.end(); ``` -------------------------------- ### Auto-Discover Headers from Objects using TypeScript and JavaScript Source: https://c2fo.github.io/fast-csv/docs/formatting/examples Explains how to automatically discover CSV headers from JavaScript objects when the `headers` option is set to `true` in fast-csv. This method is suitable for one-dimensional array rows. ```typescript import { format } from '@fast-csv/format'; const csvStream = format({ headers: true });csvStream.pipe(process.stdout).on('end', () => process.exit());csvStream.write({ header1: 'value1a', header2: 'value1b' });csvStream.write({ header1: 'value2a', header2: 'value2b' });csvStream.write({ header1: 'value3a', header2: 'value3b' });csvStream.write({ header1: 'value4a', header2: 'value4b' });csvStream.end(); ``` ```javascript const { format } = require('@fast-csv/format'); const csvStream = format({ headers: true });csvStream.pipe(process.stdout).on('end', () => process.exit());csvStream.write({ header1: 'value1a', header2: 'value1b' });csvStream.write({ header1: 'value2a', header2: 'value2b' });csvStream.write({ header1: 'value3a', header2: 'value3b' });csvStream.write({ header1: 'value4a', header2: 'value4b' });csvStream.end(); ``` -------------------------------- ### CSV Parsing with Transformed Headers using fast-csv Source: https://c2fo.github.io/fast-csv/docs/parsing/examples Demonstrates transforming CSV headers during parsing by providing a function to the `headers` option. This function maps over the original headers to create new ones. Includes error and end-of-stream handling. Input is a string. ```typescript import { EOL } from 'os'; import { parse } from '@fast-csv/parse'; const CSV_STRING = [ 'header1,header2', 'a1,b1', 'a2,b2' ].join(EOL); const stream = parse({ headers: headers => headers.map(h => h?.toUpperCase()), }) .on('error', error => console.error(error)) .on('data', row => console.log(row)) .on('end', (rowCount: number) => console.log(`Parsed ${rowCount} rows`)); stream.write(CSV_STRING); stream.end(); ``` ```javascript const { EOL } = require('os'); const { parse } = require('@fast-csv/parse'); const CSV_STRING = [ 'header1,header2', 'a1,b1', 'a2,b2' ].join(EOL); const stream = parse({ headers: headers => headers.map(h => h?.toUpperCase()), }) .on('error', error => console.error(error)) .on('data', row => console.log(row)) .on('end', (rowCount) => console.log(`Parsed ${rowCount} rows`)); stream.write(CSV_STRING); stream.end(); ``` -------------------------------- ### Change CSV Delimiter using TypeScript and JavaScript Source: https://c2fo.github.io/fast-csv/docs/formatting/examples Demonstrates how to change the default CSV delimiter from a comma (`,`) to a tab (`\t`) using the `delimiter` option in fast-csv. ```typescript import { format } from '@fast-csv/format'; const stream = format({ delimiter: '\t' }); stream.pipe(process.stdout); stream.write(['a', 'b']); stream.write(['a1', 'b1']); stream.write(['a2', 'b2']); stream.end(); ``` ```javascript const { format } = require('@fast-csv/format'); const stream = format({ delimiter: '\t' }); stream.pipe(process.stdout); stream.write(['a', 'b']); stream.write(['a1', 'b1']); stream.write(['a2', 'b2']); stream.end(); ``` -------------------------------- ### CSV Parsing with First Row as Headers using fast-csv Source: https://c2fo.github.io/fast-csv/docs/parsing/examples Demonstrates parsing CSV data where the first row is treated as headers. Setting `headers: true` converts each row into an object. Includes error and end-of-stream event handling. Input is a string. ```typescript import { EOL } from 'os'; import { parse } from '@fast-csv/parse'; const CSV_STRING = [ 'a,b', 'a1,b1', 'a2,b2' ].join(EOL); const stream = parse({ headers: true }) .on('error', error => console.error(error)) .on('data', row => console.log(row)) .on('end', (rowCount: number) => console.log(`Parsed ${rowCount} rows`)); stream.write(CSV_STRING); stream.end(); ``` ```javascript const { EOL } = require('os'); const { parse } = require('@fast-csv/parse'); const CSV_STRING = [ 'a,b', 'a1,b1', 'a2,b2' ].join(EOL); const stream = parse({ headers: true }) .on('error', error => console.error(error)) .on('data', row => console.log(row)) .on('end', (rowCount) => console.log(`Parsed ${rowCount} rows`)); stream.write(CSV_STRING); stream.end(); ``` -------------------------------- ### Quote Headers using boolean array Source: https://c2fo.github.io/fast-csv/docs/formatting/examples Configures CSV formatting to quote specific headers based on a boolean array. `quoteHeaders` takes an array where `true` indicates quoting the header at that index. This allows for selective quoting of headers. ```typescript import { format } from '@fast-csv/format'; const csvStream = format({ headers: ['header1', 'header2'], quoteHeaders: [false, true] });csvStream.pipe(process.stdout).on('end', () => process.exit());csvStream.write({ header1: 'value1a', header2: 'value2a' });csvStream.write({ header1: 'value1a', header2: 'value2a' });csvStream.write({ header1: 'value1a', header2: 'value2a' });csvStream.write({ header1: 'value1a', header2: 'value2a' });csvStream.end(); ``` ```javascript import { format } from '@fast-csv/format'; const csvStream = format({ headers: ['header1', 'header2'], quoteHeaders: [false, true] });csvStream.pipe(process.stdout).on('end', () => process.exit());csvStream.write({ header1: 'value1a', header2: 'value2a' });csvStream.write({ header1: 'value1a', header2: 'value2a' });csvStream.write({ header1: 'value1a', header2: 'value2a' });csvStream.write({ header1: 'value1a', header2: 'value2a' });csvStream.end(); ``` -------------------------------- ### Quote Headers using boolean Source: https://c2fo.github.io/fast-csv/docs/formatting/examples Enables quoting for all CSV headers. The `quoteHeaders` option is set to `true` to ensure that all header names are enclosed in quotes. This is a simple way to apply consistent quoting to headers. ```typescript import { format } from '@fast-csv/format'; const csvStream = format({ headers: true, quoteHeaders: true });csvStream.pipe(process.stdout).on('end', () => process.exit());csvStream.write({ header1: 'value1a', header2: 'value2a' });csvStream.write({ header1: 'value1a', header2: 'value2a' });csvStream.write({ header1: 'value1a', header2: 'value2a' });csvStream.write({ header1: 'value1a', header2: 'value2a' });csvStream.end(); ``` ```javascript import { format } from '@fast-csv/format'; const csvStream = format({ headers: true, quoteHeaders: true });csvStream.pipe(process.stdout).on('end', () => process.exit());csvStream.write({ header1: 'value1a', header2: 'value2a' });csvStream.write({ header1: 'value1a', header2: 'value2a' });csvStream.write({ header1: 'value1a', header2: 'value2a' });csvStream.write({ header1: 'value1a', header2: 'value2a' });csvStream.end(); ``` -------------------------------- ### Specify Column Order Without Writing Headers in Fast-CSV Source: https://c2fo.github.io/fast-csv/docs/formatting/examples Demonstrates how to specify the order of columns using the `headers` option while explicitly disabling the writing of headers by setting `writeHeaders` to `false`. This ensures consistent column order without including header names. ```typescript import { format } from '@fast-csv/format'; const csvStream = format({ headers: ['header2', 'header1'], writeHeaders: false });csvStream.pipe(process.stdout).on('end', () => process.exit());csvStream.write({ header1: 'value1a', header2: 'value2a' });csvStream.write({ header1: 'value1a', header2: 'value2a' });csvStream.write({ header1: 'value1a', header2: 'value2a' });csvStream.write({ header1: 'value1a', header2: 'value2a' });csvStream.end(); ``` ```javascript const { format } = require('@fast-csv/format'); const csvStream = format({ headers: ['header2', 'header1'], writeHeaders: false });csvStream.pipe(process.stdout).on('end', () => process.exit());csvStream.write({ header1: 'value1a', header2: 'value2a' });csvStream.write({ header1: 'value1a', header2: 'value2a' });csvStream.write({ header1: 'value1a', header2: 'value2a' });csvStream.write({ header1: 'value1a', header2: 'value2a' });csvStream.end(); ``` -------------------------------- ### CSV Parsing with Renamed Headers using fast-csv Source: https://c2fo.github.io/fast-csv/docs/parsing/examples Illustrates renaming existing headers in a CSV file while parsing. It uses the `headers` option for new names and `renameHeaders: true` to apply the renaming. Handles errors and stream completion. Input is a string. ```typescript import { EOL } from 'os'; import { parse } from '@fast-csv/parse'; const CSV_STRING = [ 'header1,header2', 'a1,b1', 'a2,b2' ].join(EOL); const stream = parse({ headers: ['a', 'b'], renameHeaders: true }) .on('error', error => console.error(error)) .on('data', row => console.log(row)) .on('end', (rowCount: number) => console.log(`Parsed ${rowCount} rows`)); stream.write(CSV_STRING); stream.end(); ``` ```javascript const { EOL } = require('os'); const { parse } = require('@fast-csv/parse'); const CSV_STRING = [ 'header1,header2', 'a1,b1', 'a2,b2' ].join(EOL); const stream = parse({ headers: ['a', 'b'], renameHeaders: true }) .on('error', error => console.error(error)) .on('data', row => console.log(row)) .on('end', (rowCount) => console.log(`Parsed ${rowCount} rows`)); stream.write(CSV_STRING); stream.end(); ``` -------------------------------- ### Transform CSV Data Synchronously with fast-csv Source: https://c2fo.github.io/fast-csv/docs/parsing/examples This snippet demonstrates how to transform CSV data synchronously using a provided transform function. The output of the transform function is then used for validation and emission. It takes CSV string input and outputs transformed rows. ```typescript import { EOL } from 'os'; import { parse } from '@fast-csv/parse'; const CSV_STRING = [ 'firstName,lastName', 'bob,yukon', 'sally,yukon', 'timmy,yukon', ].join(EOL); type UserRow = { firstName: string; lastName: string; }; type TransformedUserRow = UserRow & { properName: string; }; const stream = parse({ headers: true }) .transform( (data: UserRow): TransformedUserRow => ({ firstName: data.firstName.toUpperCase(), lastName: data.lastName.toUpperCase(), properName: `${data.firstName} ${data.lastName}`, }), ) .on('error', error => console.error(error)) .on('data', (row: TransformedUserRow) => console.log(JSON.stringify(row))) .on('end', (rowCount: number) => console.log(`Parsed ${rowCount} rows`)); stream.write(CSV_STRING); stream.end(); ``` ```javascript const { EOL } = require('os'); const { parse } = require('@fast-csv/parse'); const CSV_STRING = [ 'firstName,lastName', 'bob,yukon', 'sally,yukon', 'timmy,yukon', ].join(EOL); const stream = parse({ headers: true }) .transform( (data) => ({ firstName: data.firstName.toUpperCase(), lastName: data.lastName.toUpperCase(), properName: `${data.firstName} ${data.lastName}`, }), ) .on('error', error => console.error(error)) .on('data', (row) => console.log(JSON.stringify(row))) .on('end', (rowCount) => console.log(`Parsed ${rowCount} rows`)); stream.write(CSV_STRING); stream.end(); ``` -------------------------------- ### Change CSV Row Delimiter using TypeScript and JavaScript Source: https://c2fo.github.io/fast-csv/docs/formatting/examples Illustrates how to change the default row delimiter from a newline (`\n`) to a custom string (`||`) using the `rowDelimiter` option in fast-csv. ```typescript import { format } from '@fast-csv/format'; const stream = format({ rowDelimiter: '||' }); stream.pipe(process.stdout); stream.write(['a', 'b']); stream.write(['a1', 'b1']); stream.write(['a2', 'b2']); stream.end(); ``` ```javascript const { format } = require('@fast-csv/format'); const stream = format({ rowDelimiter: '||' }); stream.pipe(process.stdout); stream.write(['a', 'b']); stream.write(['a1', 'b1']); stream.write(['a2', 'b2']); stream.end(); ``` -------------------------------- ### Transform CSV Data Asynchronously with fast-csv Source: https://c2fo.github.io/fast-csv/docs/parsing/examples This snippet demonstrates asynchronous data transformation in fast-csv using a callback. The transform function accepts a callback to signal completion, allowing for asynchronous operations before emitting the row. It takes CSV string input and outputs transformed rows. ```typescript import { EOL } from 'os'; import { parse } from '@fast-csv/parse'; const CSV_STRING = [ 'firstName,lastName', 'bob,yukon', 'sally,yukon', 'timmy,yukon', ].join(EOL); type UserRow = { firstName: string; lastName: string; }; type TransformedUserRow = UserRow & { properName: string; }; const stream = parse({ headers: true }) .transform((data, cb): void => { setImmediate(() => cb(null, { firstName: data.firstName.toUpperCase(), lastName: data.lastName.toUpperCase(), properName: `${data.firstName} ${data.lastName}`, }), ); }) .on('error', error => console.error(error)) .on('data', row => console.log(JSON.stringify(row))) .on('end', (rowCount: number) => console.log(`Parsed ${rowCount} rows`)); stream.write(CSV_STRING); stream.end(); ``` ```javascript const { EOL } = require('os'); const { parse } = require('@fast-csv/parse'); const CSV_STRING = [ 'firstName,lastName', 'bob,yukon', 'sally,yukon', 'timmy,yukon', ].join(EOL); const stream = parse({ headers: true }) .transform((data, cb) => { setImmediate(() => cb(null, { firstName: data.firstName.toUpperCase(), lastName: data.lastName.toUpperCase(), properName: `${data.firstName} ${data.lastName}`, }), ); }) .on('error', error => console.error(error)) .on('data', row => console.log(JSON.stringify(row))) .on('end', (rowCount) => console.log(`Parsed ${rowCount} rows`)); stream.write(CSV_STRING); stream.end(); ``` -------------------------------- ### Transform Rows in CSV Data (TypeScript) Source: https://c2fo.github.io/fast-csv/docs/formatting/examples Demonstrates transforming rows in CSV data using the `.transform` method with an inline function. This method allows for synchronous row manipulation before writing to the CSV stream. It requires the '@fast-csv/format' package. ```typescript import { format } from '@fast-csv/format'; interface CsvRow { header1: string; header2: string; } const csvStream = format({ headers: true }).transform((row: CsvRow) => ({ header1: row.header1.toUpperCase(), header2: row.header2.toUpperCase(), }));csvStream.pipe(process.stdout).on('end', () => process.exit());csvStream.write({ header1: 'value1a', header2: 'value2a' });csvStream.write({ header1: 'value1a', header2: 'value2a' });csvStream.write({ header1: 'value1a', header2: 'value2a' });csvStream.write({ header1: 'value1a', header2: 'value2a' });csvStream.end(); ``` -------------------------------- ### Override Headers with Custom Set for Hash Array Rows in Fast-CSV Source: https://c2fo.github.io/fast-csv/docs/formatting/examples Shows how to override default headers with a custom set when processing hash array rows. This method is useful for defining specific column names that differ from the keys in the input objects. ```typescript import { format } from '@fast-csv/format'; const csvStream = format({ headers: ['header1', 'header2'] });csvStream.pipe(process.stdout).on('end', () => process.exit());csvStream.write([ ['h1', 'value1a'], ['h2', 'value1b'], ]);csvStream.write([ ['h1', 'value2a'], ['h2', 'value2b'], ]);csvStream.write([ ['h1', 'value3a'], ['h2', 'value3b'], ]);csvStream.write([ ['h1', 'value4a'], ['h2', 'value4b'], ]);csvStream.end(); ``` ```javascript const { format } = require('@fast-csv/format'); const csvStream = format({ headers: ['header1', 'header2'] });csvStream.pipe(process.stdout).on('end', () => process.exit());csvStream.write([ ['h1', 'value1a'], ['h2', 'value1b'], ]);csvStream.write([ ['h1', 'value2a'], ['h2', 'value2b'], ]);csvStream.write([ ['h1', 'value3a'], ['h2', 'value3b'], ]);csvStream.write([ ['h1', 'value4a'], ['h2', 'value4b'], ]);csvStream.end(); ```