Created
May 14, 2017 15:05
-
-
Save nucleardreamer/4ec816c032db094f6cded91193db6caf to your computer and use it in GitHub Desktop.
parse a stream of delimited lines
This file contains 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
const _ = require('lodash') | |
const parseDelimitedLines = function (stream, delimiter, nl, callback) { | |
let buf = '' | |
let err = null | |
let output = [] | |
let headers = [] | |
stream.on('data', function (data) { | |
buf += data | |
}) | |
stream.on('error', function (_err) { | |
err = _err | |
}) | |
stream.on('end', function () { | |
// split newlines | |
buf = buf.toString('utf8') | |
buf = buf.split(nl) | |
// grab the column headers | |
headers = buf[0].split(delimiter) | |
// get rid of the column headers | |
buf.shift() | |
// zip up headers and each line into an object | |
_.forEach(buf, function (line) { | |
var split = line.split(delimiter) | |
// make sure its not empty or one char, could be a problem for simple files | |
if (line.length > 1) { | |
output.push(_.zipObject(headers, split)) | |
} | |
}) | |
callback(err, output) | |
}) | |
} | |
module.exports = parseDelimitedLines |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment