-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
64 lines (64 loc) · 1.58 KB
/
index.js
File metadata and controls
64 lines (64 loc) · 1.58 KB
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
const { spawn } = require("child_process");
module.exports = function (args) {
let output = '';
let data = '';
let errorData = '';
let queryResolve;
let queryReject;
const handle = (error, result) => {
if (error && typeof queryReject == 'function') {
queryReject(error);
}
else if (typeof queryResolve == 'function') {
queryResolve(result);
}
queryReject = null;
queryResolve = null;
}
const computeParams = (map = []) => {
let params = '';
for (let key of Object.keys(map)) {
if (typeof map[key] == 'undefined') {
continue;
}
params += `.parameter set :${key} "${map[key]}"\n`;
}
return params;
}
this.run = (query, map) => {
data = '';
return new Promise((resolve, reject) => {
queryResolve = resolve;
queryReject = reject;
const params = computeParams(map);
shell.stdin.write(params + query + ';\n');
});
}
this.end = () => {
return new Promise((resolve, reject) => {
queryResolve = resolve;
queryReject = reject;
shell.stdin.end();
});
}
shell = spawn('sqlite3', ['-json'].concat(args));
shell.stdout.setEncoding('utf8');
shell.stderr.setEncoding('utf8');
shell.stdout.on('data', (chunk) => {
data += chunk;
try {
output = JSON.parse(data);
handle(null, output);
}
catch (error) {
// JSON.parse error due to partial data; safe to ignore;
// console.log(error);
}
});
shell.stderr.on('data', (chunk) => {
handle(chunk);
});
shell.on('close', (code) => {
handle(null, code);
});
}