Skip to content

Instantly share code, notes, and snippets.

@dylants
Created July 9, 2014 16:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dylants/31a2c09418ed78fb45db to your computer and use it in GitHub Desktop.
Save dylants/31a2c09418ed78fb45db to your computer and use it in GitHub Desktop.
Read CSV using node-csv (0.4 and above)
var csv = require("csv"),
fs = require("fs");
// the job of the parser is to convert a CSV file
// to a list of rows (array of rows)
var parser = csv.parse({
columns: function(line) {
// By defining this callback, we get handed the
// first line of the spreadsheet. Which we'll
// ignore and effectively skip this line from processing
},
skip_empty_lines: true
});
var ids = [];
var transformer = csv.transform(function(data) {
// this will get row by row data, so for example,
// this will read the first column and store it
var id = data[0];
if (id) {
ids.push(id);
}
});
// called when done with processing the CSV
transformer.on("finish", function() {
console.log("done!");
});
// create a read stream of our CSV file
var stream = fs.createReadStream("./my.csv");
// pipe the CSV file to the parser to convert to arrays,
// then to the transformer to read row by row
stream.pipe(parser).pipe(transformer);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment