UNPKG

voidspace

Version:

Transfer variables between threads, programs, and devices.

151 lines (131 loc) 3.62 kB
// A bad minifier messed up all the variable names! var WebSocket = require("ws"); var fs = require("fs"); var Voidspace = function() { this.datamap = {}; this.callback = {}; this.debug = false; }; Voidspace.prototype.on = function(a, b) { this.callback[a] = b; }; Voidspace.prototype.id = function() { return this.ws.id; }; Voidspace.prototype.connect = function(a) { var b = this.callback; if (!a) { a = "ws://127.0.0.1:3552"; } this.ws = new WebSocket(a); this.ws.on("open", function() { if (this.debug) { console.log("[VS][INFO] Websocket connected. "); } if (void 0 !== b["connect"]) { b["connect"]({ e: "connect", dest: a }); } }); this.ws.on("message", function(a, c) { if (this.debug) console.log("[VS][INBOUND] " + a); var d = JSON.parse(a); if ("set" === d.req) { this.datamap[d.tag] = d.data; console.log("[VS][INFO] " + d.tag + " was set to " + d.data); } else if ("create" === d.req) { if(b["create"]) { b["create"](d.data); } } else if ("init" === d.req) { this.datamap = d.data; } else if ("uuid" === d.req) { this.id = d.data.uuid; if(b["uuid"]) { b["uuid"](d.data); } } }); }; Voidspace.prototype.disconnect = function() {}; Voidspace.prototype.get = function(a) { return this.datamap[a]; }; Voidspace.prototype.set = function(k, b) { if(k) { if (this.debug) { console.log("[VS][INFO] Setting '" + k + "' to '" + b + "'. "); console.log("[VS][OUTBOUND] " + JSON.stringify({ req: "set", key: k, pool: this.pool, data: b })); } this.datamap[k] = b; this.ws.send(JSON.stringify({ req: "set", pool: this.pool, data: b, key: k })); } else { console.log("[VS][WARN] No key provided! Not setting value. "); } }; Voidspace.prototype.create = function(a, b) { if (this.debug) { console.log("[VS][INFO] Creating namespace '" + a + "'. "); console.log("[VS][OUTBOUND] " + JSON.stringify({ req: "create", pool: a, uuid: this.ws.id })); } this.pool = a; this.ws.send(JSON.stringify({ req: "create", pool: a })); this.callback["create"] = b; }; Voidspace.prototype.join = function(a, c) { if (this.debug) { console.log("[VS][INFO] Joining namespace '" + a + "'. "); console.log("[VS][OUTBOUND] " + JSON.stringify({ req: "join", pool: a })); } this.pool = a; this.ws.send(JSON.stringify({ req: "join", pool: a })); if(c) { c(); } }; Voidspace.prototype.save = function(a) { fs.writeFile(a, JSON.stringify(this.datamap), function(b) { if (b) return console.log(b); if (this.debug) console.log("[VS][INFO] Wrote to data file '" + a + "'. "); }); }; Voidspace.prototype.load = function(a) { fs.readFile(a, function(err, b) { if (err) throw err; else { this.datamap = JSON.parse(b.toString()); this.ws.send(JSON.stringify({ req: 'overwrite', data: this.datamap })); } if (this.debug) { console.log("[VS][INFO] Loaded data from file '" + a + "'. "); } }); }; module.exports = new Voidspace();