Skip to content

Instantly share code, notes, and snippets.

@IgorDePaula
Created December 31, 2019 15:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save IgorDePaula/74e08472548f5e7ce4c3154c99461189 to your computer and use it in GitHub Desktop.
Save IgorDePaula/74e08472548f5e7ce4c3154c99461189 to your computer and use it in GitHub Desktop.
const request = require('request'),
fs = require('fs'),
path = require('path'),
pathRead = 'http://www.inmetro.gov.br/da/registro/LAMPADAS_LED_COM_DISPOSITIVO_INTEGRADO_A_BASE.csv',
pathWrite = 'LAMPADAS_LED_COM_DISPOSITIVO_INTEGRADO_A_BASE.csv'
const downloadCsv = async (pathRead, pathWrite) => {
await request(pathRead).on('end', (err, data) => {
console.log('=> Download concluído')
fs.readFile(pathWrite, {encoding: 'utf8'}, (err, data) => {
readCsv(data, console.log)
})
}).pipe(fs.createWriteStream(pathWrite, {encoding: 'utf8'}))
}
const readCsv = (buffer, cb) => {
const result = []
const lines = buffer.split("\n")
const firstLine = lines.shift()
const header = firstLine.split(';')
result.push(lines.map(item => {
const fields = item.split(';')
const line = {}
const lineformated = header.map((item, a) =>{
line[item] = fields[a]
return line
})
return lineformated
}))
cb(result)
}
downloadCsv(pathRead, pathWrite)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment