Skip to content

Instantly share code, notes, and snippets.

@bezhermoso
Created August 2, 2016 23:40
Show Gist options
  • Save bezhermoso/b788f90cc0d601f484c62f08b8bd7b95 to your computer and use it in GitHub Desktop.
Save bezhermoso/b788f90cc0d601f484c62f08b8bd7b95 to your computer and use it in GitHub Desktop.
Parse CSV rows as objects, line-by-line.
"use strict";
const readline = require('readline');
const EventEmitter = require('events');
const dataPattern = /^['"|](.*)['"|]$/;
const trimData = function (str) {
return String(str).trim().replace(dataPattern, '$1');
}
class CSVJSONReadLine extends EventEmitter {
constructor (input, delimeter) {
super();
this.csvHeader = null;
this.delimeter = typeof delimeter == 'string' ? delimeter : ',';
this.readline = readline.createInterface({
input: input,
terminal: false
});
this.readline.on('line', (line) => {
if (this.csvHeader === null) {
this.csvHeader = line.split(this.delimeter).filter(trimData);
return;
}
const row = line.split(this.delimeter).map(trimData);
const data = this.csvHeader.reduce((d, header, i) => {
let data = row[i];
d[header] = typeof data == 'string' ? data : null;
return d;
}, {});
this.emit('row', data, this.readline);
});
this.readline.on('close', () => {
this.emit('close');
});
}
};
module.exports = CSVJSONReadLine;
"use strict";
const CSVJSONReadLine = require("./csvjson-readline");
const fs = require("fs");
var csvJSON = new CSVJSONReadLine(fs.createReadStream("/path/to/file.csv"));
csvJSON.on("row", console.log);
csvJSON.on("close", console.log);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment