Skip to content

Instantly share code, notes, and snippets.

@basperheim
Last active November 21, 2021 19:03
Show Gist options
  • Save basperheim/1a230cdbcbc5dd54d9145e59d4f1df72 to your computer and use it in GitHub Desktop.
Save basperheim/1a230cdbcbc5dd54d9145e59d4f1df72 to your computer and use it in GitHub Desktop.
Create a CSV file using NodeJS and fast-csv

Write to a CSV file using NodeJS

Outputs data to a CSV file using NodeJS.

Install the fast-csv package

Install the fast-csv NodeJS package:

npm i fast-csv

Create a simple CSV file

Create a new .js file with the following sample code:

#!/usr/bin/env node
'use strict';

const fs = require('fs');
const path = require('path');
const csv = require('fast-csv');

/**
 * Writes data stored in an object literal to a CSV file path
 **/
const createCsv = (data, filename) => {
    const csvFile = path.resolve(__dirname, filename);
    const csvStream = csv.format({ headers: true });
    
    csvStream.write(data);
    csvStream.pipe(fs.createWriteStream(csvFile, { encoding: 'utf8' } ))
    csvStream.end();
    return `Finished writing data to: ${csvFile}`;

}

const data = {
    'Col 1': 'Foo',
    'Col 2': 'Bar',
    'Col 3': 42,
}

const result = createCsv(data, 'test.csv');
console.log(result);

Create a CSV file with set headers/columns

Another example that passes an an nested array of row arrays with set headers:

#!/usr/bin/env node
'use strict';

const fs = require('fs');
const path = require('path');
const csv = require('fast-csv');

/**
 * Writes data stored in an object literal to a CSV file path
 **/
const createCsv = (data, filename) => {
    const csvFile = path.resolve(__dirname, filename);
    
    // pass the array of headers to format() method
    const csvStream = csv.format({ headers: data.headers });

    // loop over nested row arrays
    const arr = data.rows;
    for (let i = 0; i<arr.length; i++) {
        let row = arr[i];
        csvStream.write( row );
    }
    csvStream.end();
    csvStream.pipe(fs.createWriteStream(csvFile, { encoding: 'utf8' } ))    
    return `Finished writing data to: ${csvFile}`;

}

const data = {
    headers: ['Col 1', 'Col 2'],
    rows: [
        ['Foo', 'Bar'],
        ['Hello', 'World'],
        ['Life', 42],
        ['Test 1', 'Test 2']
    ]
};

const result = createCsv(data, 'test.csv');
console.log(result);

Run the NodeJS script to output data to CSV

In a terminal run the code with: node path/to/nodejs/script.js

@basperheim
Copy link
Author

nodejs-fast-csv-fs-write-csv-file-example

@basperheim
Copy link
Author

nodejs-fast-csv-data-with-set-headers

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment