Created
August 2, 2016 23:40
-
-
Save bezhermoso/b788f90cc0d601f484c62f08b8bd7b95 to your computer and use it in GitHub Desktop.
Parse CSV rows as objects, line-by-line.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"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; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"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