Last active
June 10, 2018 21:46
-
-
Save marco-souza/59df0f91b3cd3c9bb94742318944d7ca to your computer and use it in GitHub Desktop.
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 request = require('request') | |
const listaentrada = require('./data/ListaCompletaESC.json') | |
const entrestrings = (nastring, inicio, fim) => { | |
const test = nastring.match(new RegExp(inicio + '(.*)' + fim)) | |
if (test) { | |
let stringentre = nastring.match(new RegExp(inicio + '(.*)' + fim))[1] | |
stringentre = stringentre.trim() | |
return stringentre | |
} else return ('vazio') | |
} | |
let listacarregada = [] | |
const carregar = item => { | |
const ANO = 2018 | |
// Variable declaration decomposing/spreading | |
// an object (es6 syntax) supported on node | |
const { | |
CNPJ: cnpj, | |
MUN: mun, | |
UF: uf, | |
RS | |
} = item | |
const url = 'http://www.fnde.gov.br/pls/internet_pdde/internet_fnde.PDDEREX_4_PC?p_ano=' + ANO + '&b_ver=3&p_cgc=' + cnpj + '&p_tip=E&p_prog=02' | |
return request(url, (err, resp, body) => { | |
if (err) console.log(err) | |
else { | |
const CODIGO = entrestrings(body, '11%\'>\n ', '\n </td>\n <td valign') | |
const FANTASIA = entrestrings(body, '9%\'>\n ', '\n </td>') | |
// Item to be added in listacarregada | |
const newItem = { | |
FANTASIA, | |
CODIGO, | |
cnpj, | |
uf, | |
mun, | |
RS | |
} | |
if (CODIGO === 'vazio') console.log('Não Adicionado') | |
else if (listacarregada.indexOf(newItem) === -1) { | |
// add new item | |
listacarregada.push(newItem) | |
// Show some info | |
console.log('Um item adicionado : \n' + newItem) | |
console.log('Todos os itens até agora \n' + listacarregada) | |
} | |
} | |
return listacarregada | |
}) | |
} | |
Promise | |
.all(listaentrada.map(item => carregar(item))) | |
.then(() => fs.writeFile('./test', JSON.stringify(listacarregada), err => { | |
if (err) { | |
return console.log(err) | |
} | |
console.log('The file was saved!') | |
})) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Dicas
var
comlet
econst
. Pode causar problema com projetos mais complexosconst
elet
, nessa ordem. É sempre bom evitar mutabilidade de objetos, mas quando não é possível,let
é mais recomendado quevar
, pelo modo como o escopo é organizado() => {}
é mais elegante e leve para o node, ele não precisa criar um novo escopo, assim como ocorre no uso defunction