csv-writer

repository·master·Indexed 42 days ago

https://github.com/ryu1kn/csv-writer

A utility for converting objects or arrays into CSV strings or writing them directly to files, adhering to the RFC 4180 standard. Version 1.6.0 provides specialized tools including createObjectCsvWriter, createArrayCsvWriter, and stringifier equivalents to handle data mapping, custom delimiters, and file encoding.

Tokens
3.5K
Snippets
14
Records
25
Agent score
54%

What's inside csv-writer

  1. Write objects to a CSV file with createObjectCsvWriter

    master

    Use createObjectCsvWriter to convert an array of objects into a CSV file. You can define a header with both an id (the key in your object) and a title (the column name in the CSV). If you provide only strings in the header array, no header line will be written to the file.

    To write multiple batches of records to the same file, you must await the promise returned by writeRecords before calling it again to ensure data integrity.

    const createCsvWriter = require('csv-writer').createObjectCsvWriter;
    const csvWriter = createObjectCsvWriter({
        path: 'path/to/file.csv',
        header: [
            {id: 'name', title: 'NAME'},
            {id: 'lang', title: 'LANGUAGE'}
        ]
    });
    
    const records = [
        {name: 'Bob',  lang: 'French, English'},
        {name: 'Mary', lang: 'English'}
    ];
    
    csvWriter.writeRecords(records)
        .then(() => {
            console.log('...Done');
        });
  2. Convert objects or arrays to a CSV string

    master

    If you need a CSV string instead of writing directly to a file, use createObjectCsvStringifier or createArrayCsvStringifier. These return a stringifier object that provides methods to generate the header string and the record strings separately.

    const createCsvStringifier = require('csv-writer').createObjectCsvStringifier;
    const csvStringifier = createCsvStringifier({
        header: [
            {id: 'name', title: 'NAME'},
            {id: 'lang', title: 'LANGUAGE'}
        ]
    });
    
    const records = [
        {name: 'Bob',  lang: 'French, English'},
        {name: 'Mary', lang: 'English'}
    ];
    
    console.log(csvStringifier.getHeaderString());
    // => 'NAME,LANGUAGE\n'
    
    console.log(csvStringifier.stringifyRecords(records));
    // => 'Bob,"French, English"\nMary,English\n'
  3. Write arrays to a CSV file with createArrayCsvWriter

    master

    Use createArrayCsvWriter when your data is structured as an array of arrays rather than an array of objects. The header option accepts an array of strings representing the column titles.

    const createCsvWriter = require('csv-writer').createArrayCsvWriter;
    const csvWriter = createCsvWriter({
        header: ['NAME', 'LANGUAGE'],
        path: 'path/to/file.csv'
    });
    
    const records = [
        ['Bob',  'French, English'],
        ['Mary', 'English']
    ];
    
    csvWriter.writeRecords(records)
        .then(() => {
            console.log('...Done');
        });
  4. Configure Object CSV headers

    master

    When using object-based CSV writers or stringifiers, headers can be defined using ObjectHeaderItem[] or string[].

    • ObjectHeaderItem[]: An array of objects where each object specifies an id (the key in the source object) and a title (the column name in the CSV).
    • string[]: An array of strings representing the column names.
  5. CsvWriter#writeRecords(records)

    master
    Writes a collection of records to the file. The records parameter must be an Iterator. Depending on whether createObjectCsvWriter or createArrayCsvWriter was used, the iterator should yield objects or arrays respectively.
  6. Reference: createArrayCsvWriter parameters

    master

    Configuration options for createArrayCsvWriter(params):

    ParameterTypeDefaultDescription
    pathstringRequiredPath to a write file
    headerArray<string>(optional)Array of field titles
    fieldDelimiterstring,Only , or ; allowed
    recordDelimiterstring\nOnly \n (LF) or \r\n (CRLF) allowed
    alwaysQuotebooleanfalseIf true, double-quotes all fields
    encodingstringutf8File encoding
    appendbooleanfalseIf true, appends to file. Note: Header will NOT be written if append is true.
  7. Reference: createObjectCsvWriter parameters

    master

    Configuration options for createObjectCsvWriter(params):

    ParameterTypeDefaultDescription
    pathstringRequiredPath to a write file
    headerArray<{id, title} | string>RequiredArray of objects (id and title) or strings (field IDs). Header line is only written if using objects.
    fieldDelimiterstring,Only , or ; allowed
    recordDelimiterstring\nOnly \n (LF) or \r\n (CRLF) allowed
    headerIdDelimiterstringundefinedPath to a value in a nested object
    alwaysQuotebooleanfalseIf true, double-quotes all fields
    encodingstringutf8File encoding
    appendbooleanfalseIf true, appends to file. Note: Header will NOT be written if append is true.
  8. Reference: createObjectCsvStringifier parameters

    master

    Configuration options for createObjectCsvStringifier(params):

    ParameterTypeDefaultDescription
    headerArray<{id, title} | string>RequiredArray of objects (id and title) or strings (field IDs)
    fieldDelimiterstring,Only , or ; allowed
    recordDelimiterstring\nOnly \n (LF) or \r\n (CRLF) allowed
    headerIdDelimiterstringundefinedPath to a value in a nested object
    alwaysQuotebooleanfalseIf true, double-quotes all fields