Skip to content

Instantly share code, notes, and snippets.

@alexmachina
Created February 12, 2019 18:55
Show Gist options
  • Save alexmachina/dc3e9027b48a0023c98ee38d794a8df7 to your computer and use it in GitHub Desktop.
Save alexmachina/dc3e9027b48a0023c98ee38d794a8df7 to your computer and use it in GitHub Desktop.
CSV reading with nodejs
const fs = require('fs');
function fromCSVFile (path) {
// helper funcs
const removeEmpty = a => a.length !== 0
const removeLeading = a => a !== '';
const euQuero = str => Boolean({
'mundo': true,
'regional': true,
}[str]);
return new Promise((resolve, reject) =>
fs.readFile(path, 'utf8', (err, csv) => {
if (err) reject(err);
else {
const linesArr = csv.split('\n');
const rows = csv.split('\n');
const header = rows.shift().split(';').filter(euQuero);
const body = rows.map(r => r.split(';').filter(removeLeading));
const result = body.map(dataRow =>
dataRow.reduce((acc, value, i) => Object.assign({}, acc, { [header[i]]: value }), [])
).filter(removeEmpty);
resolve(result);
}
})
);
}
const tree = arr => arr.map(obj =>
Object.values(obj).reduce((acc, value) => (
acc.concat( ' > ').concat(value)
)
))
fromCSVFile('/home/alex/Downloads/gupy_funcionarios.csv').then(a => {
console.log('Objeto ::: ', a);
console.log('[Arvore] ::: ', tree(a)[0])
});
@alexmachina
Copy link
Author

this could become a lib?

missing:

  • error boundaries
  • separator
  • validation

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment