forked from paviro/MMM-syslog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnode_helper.js
78 lines (67 loc) · 1.92 KB
/
node_helper.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
/* global Module */
/* Magic Mirror
* Module: MMM-syslog2
*
* By Paul-Vincent Roll http://paulvincentroll.com
* MIT Licensed.
*/
const NodeHelper = require("node_helper");
const url = require("url");
const fs = require("fs");
module.exports = NodeHelper.create({
start: function() {
this.expressApp.get('/syslog2', (req, res) => {
var query = url.parse(req.url, true).query;
var message = query.message;
var type = query.type;
var silent = query.silent || false;
if (message == null && type == null){
res.send({"status": "failed", "error": "No message and type given."});
}
else if (message == null){
res.send({"status": "failed", "error": "No message given."});
}
else if (type == null) {
res.send({"status": "failed", "error": "No type given."});
}
else {
var log = {"type": type, "message": message, "silent": silent, "timestamp": new Date()};
res.send({"status": "success", "payload": log});
this.sendSocketNotification("NEW_MESSAGE", log);
this.storeLog(log);
}
});
},
socketNotificationReceived: function(notification, payload) {
if(notification === "CONNECT"){
this.logFile = payload.logFile;
this.loadLogs();
this.max = payload.max;
}
},
storeLog: function(log){
this.logs.push(log);
while(this.logs.length > this.max){
this.logs.shift();
}
fs.writeFileSync(this.logFile, JSON.stringify({"messages": this.logs}), 'utf8');
},
loadLogs: function(){
if(this.fileExists(this.logFile)){
this.logs = JSON.parse(fs.readFileSync(this.logFile, 'utf8')).messages;
for(var i = 0; i < this.logs.length; i++){
this.sendSocketNotification("NEW_MESSAGE", this.logs[i]);
}
} else {
this.logs = [];
}
},
fileExists: function(path){
try {
return fs.statSync(path).isFile();
} catch(e) {
console.log("No log file found.");
return false;
}
}
});