-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
57 lines (57 loc) · 1.54 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
const { spawn } = require("child_process");
module.exports = (args) => {
return new Promise((dbResolve, dbReject) => {
try {
let output = '';
let data = '';
let sql = {};
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;
}
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);
});
sql.run = (query) => {
data = '';
return new Promise((resolve, reject) => {
queryResolve = resolve;
queryReject = reject;
shell.stdin.write(query);
});
}
sql.end = () => {
return new Promise((resolve, reject) => {
queryResolve = resolve;
queryReject = reject;
shell.stdin.end();
});
}
dbResolve(sql);
}
catch(error) {
dbReject(error);
}
});
}