forked from djwillcaine/Bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.js
60 lines (54 loc) · 1.26 KB
/
util.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
var http = require('http')
, https = require('https')
, fs = require('fs')
, logs = "";
process.on('uncaughtException', function(err) {
exports.log('Uncaught Exception: ' + err);
});
setInterval(function(){
exports.save();
}, 3600000);
exports.save = function(data, callback) {
try {
var stream = fs.createWriteStream("db.json", {
flags: 'w'
});
stream.end(JSON.stringify(data));
stream.on('finish', function() {
exports.log("Saved database to file.");
if (typeof callback === 'function') callback();
});
} catch(err) {
exports.log("Error whilst saving database to file: " + err);
}
}
exports.getReq = function(url, json, func, secure) {
protocol = secure ? https : http;
protocol.get(url, function(res) {
var body = '';
res.on('data', function(chunk) {
body += chunk;
});
res.on('end', function() {
var resp = body;
if (json == true) {
try {
var resp = JSON.parse(body);
} catch (err) {
resp = null;
}
}
func(resp);
});
}).on('error', function(e) {
exports.log("Got error: " + e);
});
}
exports.log = function(msg) {
time = new Date().toISOString().replace("T", " ").slice(0, 16);
console.log(time + " " + msg);
logs += time + " " + msg + "<br />";
}
exports.getLog = function() {
return logs;
}