Skip to content

Instantly share code, notes, and snippets.

@ben-bradley
Last active August 29, 2015 14:12
Show Gist options
  • Save ben-bradley/0faa43e14ef57b8cb725 to your computer and use it in GitHub Desktop.
Save ben-bradley/0faa43e14ef57b8cb725 to your computer and use it in GitHub Desktop.
Objectifying a CSV with streams!
var objectify = require('./objectify'),
fs = require('fs');
var source = fs.createReadStream(__dirname+'/file.csv');
var objects = source.pipe(objectify);
objects.on('data', function(object) {
// do something with the object
});
objects.on('end', function() {
// done reading objects from the CSV
});
var stream = require('stream');
var objectify = new stream.Transform({
objectMode: true
});
objectify._buffer = '';
objectify._transform = function (data, encoding, cb) {
this._buffer += data;
var lines = this._buffer.split('\n');
while (lines.length > 1) {
this.push(objection(lines.shift()));
}
this._buffer = lines.join('\n');
cb();
};
module.exports = objectify;
// This is a custom parsing function to build the object
function objection(line) {
var row = line.split(',');
return {
individualId: row[0],
logDate: new Date(row[1]),
actionDate: (row[2]) ? new Date(row[2]) : null,
key: row[3],
value: (row[4]) ? row[4] : null
};
}
function isDate(date) {
return date instanceof Date && !isNaN(date.valueOf());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment