node package manager

csv-manipulator

Synopsis

Provides helper methods for reading, writing, and quickly making manipulations to CSV-formatted files.

The module is designed to ease the writing of one-off data manipulation scripts, so the APIs for reading, writing, and mutating CSV files are deliberately simple and may not be heavily customizable.

Documentation

Importing

You can use the csv-manipulator library in your code by requiring it:

var csv = require('csv-manipulator');

Methods

  1. csv.readCsv
  2. csv.writeCsv
  3. csv.updateRows

csv.readCsv

Syntax

csv.readCsv(fileName, callback)

Reads a CSV-formatted file fileName into a list of rows, executing callback when the operation completes.

The CSV file passed to this function should have a row of headers as the first row in the file, as the headers will be used to determine the property names of each row object loaded from the file.

Available since version 0.0.2.

Parameters

  • fileName: Name of CSV file to load. The first row of data in the file is assumed to be named column headers.
  • callback: Callback function to execute after the CSV file is loaded. Takes the following parameters:
    • err: An Error object if an error occurred. Otherwise, null.
    • rows: If an error did not occur, this will be a list of rows loaded from the CSV file. Each row is represented as an object which has property names corresponding to the header of each column. The value of each property will the a String value of the corresponding column.

Example

Given the following CSV file (named "employee.csv"):

"Name","JobTitle","Age"
"Alfred","Developer","31"
"Blake","Business Analyst","35"

The data can be loaded with csv.readCsv:

var csv = require('csv-manipulator');

csv.readCsv('data.csv', function(err, rows) {
    // if an error occurred, log it and exit
    if (err) {
        console.log(err.stack);
        return;
    }

    // now we can work with the "rows" loaded from "employee.csv"

    // This will print "Business Analyst"
    console.log(rows[1].JobTitle);

	// This will print "31"
    console.log(rows[0].Age);

    var totalAge = 0;
    rows.forEach(function(row) {
        // NB: This value is a String, so we need to coerce it to a number
        totalAge += (+row.Age);
    });

    console.log('Average employee age: ' + ( totalAge / rows.length));
});

csv.writeCsv

Syntax

csv.writeCsv(rows, fileName, callback)

The list of rows specified will be written in a CSV-format to the file given by fileName. After the file has been written, the callback function will be executed.

The CSV file written by this function will have a row of headers as the first row in the file.

Available since version 0.0.3.

Parameters

  • rows: List of rows to write to the CSV file. Each row should be represented as an object which has property names corresponding to the header of each column. The value of each property will be written as a String value in the corresponding column.
  • fileName: Name of CSV file to write. The first row of data written to the file will be named column headers based on the object property names in the list of rows.
  • callback: Callback function to execute after the CSV file is written. Takes the following parameters:
    • err: An Error object if an error occurred. Otherwise, null.

Example

The data can be written with csv.readCsv:

var csv = require('csv-manipulator');

var rows = [
	{
		Name: 'Alfred',
		JobTitle: 'Developer',
		Age: '31'
	},
	{
		Name: 'Blake',
		JobTitle: 'Business Analyst',
		Age: '35'
	}
];

csv.writeCsv(rows, 'employee.csv', function(err) {
    // if an error occurred, log it and exit
    if (err) {
        console.log(err.stack);
        return;
    }

    console.log('CSV file was written successfully!');
});

The script above will generate a document equivalent to the following "employee.csv" file:

"Name","JobTitle","Age"
"Alfred","Developer","31"
"Blake","Business Analyst","35"

csv.updateRows

Syntax

csv.updateRows(fileName, iterFn, [callback])

Loads the file specified by fileName and runs the iterFn function for each row in the file. After processing all rows, writes any updates made to the rows back to fileName. The optional callback function will be run after the processing has been completed.

The CSV file handled by this function should have a row of headers as the first row in the file.

Available since version 0.0.1.

Parameters

  • fileName: Name of CSV file to update. The first row of data written to the file must be named column headers and will be used as the property names for the row objects passed to the iterFn.
  • iterFn: Invoked for each row in the CSV file. Any mutation made to the row will be written back to the file specified by fileName. Takes the following parameters:
    • row: A row object loaded from the CSV file. The property names on this object will correspond with the headers of the CSV file and the values will be String values loaded from the corresponding columns.
  • callback: Optional. Callback function to execute after the operation has completed. If this function is not provided, a default will be used which logs the number of rows processed by the operation. Takes the following parameters:
    • err: An Error object if an error occurred. Otherwise, null.
    • result: If an error did not occur, this will be an object with details about the result of the operation. Has the following properties:
      • totalRows: The number of rows processed by the operation

Example

Given the following CSV file (named "employee.csv"):

"Name","JobTitle","Age"
"Alfred","Developer","31"
"Blake","Business Analyst","35"

The following script can be used to increase the "Age" field of each employee by 1:

var csv = require('csv-manipulator');

// We can run updateRows with a callback that will run when processing
// completes, like so:
csv.updateRows('employee.csv', function(row) {
	// NB: This value is a String, so we need to coerce it to a number
    row.Age = (row.Age + 1);
}, function(err, result) {
	// handle an Error, if one occurred
	if (err) {
		console.log(err.stack);
		return;
	}

	// Put any additional logic in here to run after the operation
	// has completed, if needed.

	console.log('Processed ' + result.totalRows + ' rows');
});

// If we don't need to perform any processing after the "updateRows"
// operation is complete, we can omit the second callback:
csv.updateRows('employee.csv', function(row) {
	// NB: This value is a String, so we need to coerce it to a number
    row.Age = (row.Age + 1);
});

This will generate a result equivalent to the following output in the "employee.csv" file:

"Name","JobTitle","Age"
"Alfred","Developer","32"
"Blake","Business Analyst","36"