Skip to content

Instantly share code, notes, and snippets.

@erik4github
Last active October 16, 2020 05:47
Show Gist options
  • Save erik4github/36d6584cd3e1992b2bf354a020b48858 to your computer and use it in GitHub Desktop.
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.
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