Created
February 12, 2019 18:55
-
-
Save alexmachina/dc3e9027b48a0023c98ee38d794a8df7 to your computer and use it in GitHub Desktop.
CSV reading with nodejs
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'); | |
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]) | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
this could become a lib?
missing: