-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
76 lines (66 loc) · 1.69 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
const {cleanup} = require('./lib/index')
process.on('uncaughtException', function (err) {
console.log(err);
cleanup(() => {
process.exit(1)
})
})
process.on('unhandledRejection', function(reason, p){
console.log("Unhandled Rejection, reason: ", reason);
cleanup(() => {
process.exit(1)
})
});
const readline = require('readline')
const cnpj = require('./lib/index')
const cookies = process.argv[2]
if (!cookies) {
console.log('Informe session-token')
process.exit(1)
}
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
terminal: false,
})
let nextTask = Promise.resolve()
const processed = {}
rl.on('line', function (line) {
line = line.replace(/[ \.\-/]/g, '')
if (!line) {
rl.close()
return
}
if (line.length === 11) {
return
}
if (processed[line]) {
return
}
processed[line] = true
if (cnpj.exists(line)) {
return
}
const awaiter = nextTask
nextTask = new Promise((resolve, reject) => {
awaiter.then(() => {
fetchOne(line).then(resolve, reject)
})
})
})
function fetchOne(line) {
console.log('Processing: ', line, 'fetching...')
return cnpj.fetchCnpj(line, cookies)
.then(response => {
const {qsa} = cnpj.processCnpj(response)
const {info} = response
cnpj.found(line, Object.assign(info, { qsa }))
})
.catch(err => {
cnpj.failed(line, err)
console.error(' Error:', err.code, err.message)
if (err.unrecoverable || err.code === 'ECONNRESET') {
throw err
}
})
}