Skip to content

Instantly share code, notes, and snippets.

@AndreasMadsen
Created August 2, 2012 17:10
Show Gist options
  • Save AndreasMadsen/3238808 to your computer and use it in GitHub Desktop.
Save AndreasMadsen/3238808 to your computer and use it in GitHub Desktop.
var fs = require('fs');
var util = require('util');
var Stream = require('stream');
var file = fs.createReadStream('file.csv');
var parser = new CSV();
// values will be emitted
parser.on('value', function (value) {
console.log(value);
});
file.pipe(parser);
function CSV() {
Stream.call(this);
this.buffer = '';
this.writable = true;
}
util.inherits(CSV, Stream);
CSV.prototype.write = function (chunk) {
var res = (this.buffer + chunk.toString()).split(',');
// pull out the last data
this.buffer = res.pop();
res.forEach(this.emit.bind(this, 'value'));
};
CSV.prototype.end = function (chunk) {
this.write(chunk);
this.emit('value', this.buffer);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment