-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
206 lines (183 loc) · 5.31 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
#!/usr/bin/env node
const nexline = require('nexline');
const fs = require('fs');
const countdown = require('countdown');
const { Client } = require('@elastic/elasticsearch');
const ora = require('ora');
const ProgressBar = require('progress');
const colors = require('colors');
const spinner_1 = ora('Getting the length of the file');
const shell = require('shelljs');
const program = require('commander');
const axios = require('axios');
let file, separator, columns, lines, createNewIndex, index, connection;
program
.name('duckimport')
.option('-c, --config <path>', 'config file path')
.option('-i, --inline <configString>', 'base64 encoded config object');
program.on('--help', function () {
console.log('');
console.log('Examples:');
console.log(` $ ${program._name} -c ./config.json`);
console.log(` $ ${program._name} -i NDJjNGVx........GZzZGY=\n`);
console.log(
colors.blue(
'For questions and error reports please visit the github repository: https://github.com/ofarukcaki/duckimport'
)
);
});
program.parse(process.argv);
if (!program.config && !program.inline) {
console.log(
colors.red('You must provide a config. Type "--help" for more details.')
);
process.exit(1);
} else if (program.config) {
var _config = JSON.parse(fs.readFileSync(program.config));
(file = _config.file),
(separator = _config.separator ? _config.separator : _config.seperator),
(columns = _config.columns),
(lines = _config.lines),
(createNewIndex = _config.createNewIndex),
(index = _config.index),
(connection = _config.client);
} else if (program.inline) {
var _config = JSON.parse(Buffer.from(program.inline, 'base64').toString());
(file = _config.file),
(separator = _config.separator ? _config.separator : _config.seperator),
(columns = _config.columns),
(lines = _config.lines),
(createNewIndex = _config.createNewIndex),
(index = _config.index),
(connection = _config.client);
}
const client = new Client(connection);
let s = null;
console.table({
file: file,
separator: separator,
columns: columns.join(),
'target index': index.index,
});
let bar = null;
const isSmall = smallerThan2GB(file);
if (isSmall) {
const lc = getLength(file);
bar = new ProgressBar(
`Importing ${colors.cyan('[:bar]')} :percent :rate/lps ${
'ETA:'.bold
} :etas`.yellow,
{
total: lc,
width: 50,
}
);
} else {
console.log(
colors.yellow(
"File size exceeds 2GB, hence the tool won't calculate the length of the file. You won't see a progress bar but logs instead."
)
);
}
async function main() {
const fd = fs.openSync(file, 'r');
const nl = nexline({
input: fd, // input can be file, stream, string and buffer
});
let dataset = [];
let lc = 0;
let total = 0;
s = new Date(Date.now());
console.log('> Started');
while (true) {
let line = await nl.next();
if (line) line = line.trim(); //Remove the '\n' from the end of the line
lc++;
let obj = {};
try {
let splitted = line.split(separator);
for (let i = 0; i < columns.length; i++) {
obj[columns[i]] = splitted[i];
}
dataset.push(obj); // push the object if != {}
} catch (error) {}
if (lc % lines === 0) {
let err = await pushElastic(dataset);
if (isSmall) {
bar.tick(dataset.length);
}
if (err) {
console.log('There is an error', err);
} else if (!isSmall) {
total += lines;
console.log(`${lines} lines imported Total: ${total}`);
}
dataset = [];
}
if (line === null) {
// push remainders
let err = await pushElastic(dataset);
if (err) {
console.log('There is an error');
} else if (!isSmall) {
total += lines;
console.log(`${lines} lines imported Total: ${total}`);
}
if (isSmall) {
bar.tick(dataset.length);
}
dataset = [];
// If all data is read, returns null
console.log('> Completed');
break;
}
}
fs.closeSync(fd);
}
let isFirstTime = true;
async function pushElastic(dataset) {
if (isFirstTime && createNewIndex) {
// setup the index
await client.indices.create(index, { ignore: [400] });
}
const _index = index.index;
const body = dataset.flatMap((doc) => [{ index: { _index } }, doc]);
let errors = null;
try {
const { body: bulkResponse } = await client.bulk({ refresh: true, body });
errors = bulkResponse.errors;
} catch (error) {
console.log(
colors.red(
'There is a problem with Elasticsearch connection, make sure your elesticsearch server is running and your credentials are correct.'
)
); // undefined error?
process.exit(2);
}
isFirstTime = false;
return errors;
}
main();
function smallerThan2GB(file) {
if (fs.statSync(file).size < 2147483649) {
return true;
} else {
return false;
}
}
function getLength(file) {
spinner_1.start();
const out = shell.exec(`wc -l ${file}`, { silent: true }).stdout.trim();
const regex = /(\d*)\s.*/;
const lc = parseInt(regex.exec(out)[1]);
spinner_1.stopAndPersist({ symbol: '>', text: `${lc} lines detected.` });
return lc;
}
process.on('beforeExit', (code) => {
console.log(
colors.yellow(
'\nTime took: '.bold +
countdown(s, null, countdown.ALL, NaN, 0).toString()
)
);
});