Last active
October 16, 2020 05:47
-
-
Save erik4github/36d6584cd3e1992b2bf354a020b48858 to your computer and use it in GitHub Desktop.
A basic CSV reader in node. Doesn't account for things like commas in row or header values.
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
const fs = require('fs'); | |
const { once } = require('events'); | |
const readline = require('readline'); | |
const zip = (keys, vals) => | |
keys.reduce((currentObj, prop, idx) => { | |
currentObj[prop] = vals[idx]; | |
return currentObj; | |
}, {}); | |
const parseCSV = async (csvFile) => { | |
let i = 0; | |
let cols = []; | |
let rows = []; | |
let data = []; | |
const stream = fs.createReadStream(csvFile, { encoding: 'utf-8' }) | |
const readInterface = readline.createInterface({ | |
input: stream, | |
output: process.stdout, | |
terminal: false | |
}); | |
readInterface.on('line', (line) => { | |
i++; | |
let row; | |
if (i === 1) { | |
cols = line.split(','); | |
} else { | |
row = line.split(','); | |
rows.push(row); | |
} | |
}); | |
await once(readInterface, 'close'); | |
data = rows.map(row => zip(cols, row)); | |
return data; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment