/
ipc.js
61 lines (51 loc) 路 1.14 KB
/
ipc.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
'use strict';
const Emittery = require('../emittery');
// `process.channel` was added in Node.js 7.1.0, but the channel was available
// through an undocumented API as `process._channel`.
const channel = process.channel || process._channel;
const emitter = new Emittery();
process.on('message', message => {
if (!message.ava) {
return;
}
switch (message.ava.type) {
case 'options':
emitter.emit('options', message.ava.options);
break;
case 'peer-failed':
emitter.emit('peerFailed');
break;
case 'pong':
emitter.emit('pong');
break;
default:
break;
}
});
exports.options = emitter.once('options');
exports.peerFailed = emitter.once('peerFailed');
function send(evt) {
if (process.connected) {
process.send({ava: evt});
}
}
exports.send = send;
function unref() {
channel.unref();
}
exports.unref = unref;
let pendingPings = Promise.resolve();
function flush() {
channel.ref();
const promise = pendingPings.then(() => {
send({type: 'ping'});
return emitter.once('pong');
}).then(() => {
if (promise === pendingPings) {
unref();
}
});
pendingPings = promise;
return promise;
}
exports.flush = flush;