-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
72 lines (55 loc) · 2.22 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
var EventEmitter = require('./EventEmitter.js');
var stderr = require('system').stderr;
var stdin = require('system').stdin;
(function(window) {
"use strict";
function sleepyhollow() {
// the modified event-emitter bridge
var sleepyhollow = new EventEmitter();
_emit = sleepyhollow.emit;
// each message will get it's own ID
var msgId = 0;
sleepyhollow.emit = function(event, message) {
if (!message) message = " ";
msgId++;
// local emit, for other subscribers
_emit.apply(sleepyhollow, Array.prototype.slice.call(arguments, 0));
// if this event is an ack, bolt
if (event == "ack") return;
// experiments show that 4096 is the only safe MTU
// stringify and chunk out writes
JSON.stringify(message)
.match(/.{1,4096}/g)
.forEach(function(message, index, arr) {
write({
msgId: msgId,
// if there is more than one index, it's multipart
isMultipart: arr.length > 1,
// EOF there are no more indicies left to pass
isEOF: (index == arr.length - 1),
event: event,
message: message
});
});
}
// custom write <> read bridge
function write(obj) {
stderr.write(JSON.stringify(obj) + "\n");
if (obj.event !== "ack") read();
}
function read() {
var data = stdin.readLine();
try { data.split("\v").forEach(_read); }
catch (e) { throw new Error(data); }
}
function _read(data) { return _readLine(JSON.parse(data)); }
function _readLine(obj) {
if (obj.event !== "ack") write({ event: "ack", message: obj });
_emit.apply(sleepyhollow, [obj.event, obj.message]);
}
// minimal writing to make sure the Node side doesn't have to buffer
setInterval(function() { write({ "event" : "syn" }); }, 1e3);
return sleepyhollow;
}
module.exports = sleepyhollow;
})(this);