-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathindex.js
72 lines (67 loc) · 1.82 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
const fs = require('fs');
const path = require('path');
const mkdirp = require('mkdirp');
const SqliteToJson = module.exports = function SqliteToJson(opts) {
opts = opts || {};
if (!opts.client) {
throw new Error('No sqlite3 client provided.');
}
this.client = opts.client;
};
SqliteToJson.prototype.tables = function (cb) {
var query = "SELECT name FROM sqlite_master WHERE type='table'";
this.client.all(query, function (err, tables) {
if (err) {
return cb(err);
}
cb(null, tables.map(function (result) {
return result.name;
}));
});
};
SqliteToJson.prototype.save = function (table, dest, cb) {
if (typeof cb !== 'function') {
throw new Error('No callback specified.');
}
if (!dest) {
return cb(new Error('No destination file specified.'));
}
this._dataFor(table, function (dataErr, tableData) {
if (dataErr) {
cb(dataErr);
} else {
mkdirp(path.dirname(dest), function (mkdirErr) {
if (mkdirErr) {
cb(mkdirErr);
} else {
fs.writeFile(dest, JSON.stringify(tableData), function (writeErr) {
if (writeErr) {
cb(writeErr);
} else {
cb(null);
}
});
}
});
}
});
};
SqliteToJson.prototype.all = function(cb) {
var self = this;
this.tables(function (err, tables) {
if (err) return cb(err);
var ret = {};
function loop (i) {
if (i === tables.length) cb(null, ret);
else self._dataFor(tables[i], function (dataErr, tableData) {
if (dataErr) cb(dataErr);
else loop(i + 1, ret[tables[i]] = tableData);
})
}
loop(0);
})
};
SqliteToJson.prototype._dataFor = function (table, cb) {
// apparently you can't used named params for table names?
this.client.all('SELECT * FROM '+table, cb);
};