1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 | const {helper} = require('./helper');
|
17 |
|
18 |
|
19 |
|
20 |
|
21 | class PipeTransport {
|
22 | |
23 |
|
24 |
|
25 |
|
26 | constructor(pipeWrite, pipeRead) {
|
27 | this._pipeWrite = pipeWrite;
|
28 | this._pendingMessage = '';
|
29 | this._eventListeners = [
|
30 | helper.addEventListener(pipeRead, 'data', buffer => this._dispatch(buffer))
|
31 | ];
|
32 | this.onmessage = null;
|
33 | this.onclose = null;
|
34 | }
|
35 |
|
36 | |
37 |
|
38 |
|
39 | send(message) {
|
40 | this._pipeWrite.write(message);
|
41 | this._pipeWrite.write('\0');
|
42 | }
|
43 |
|
44 | |
45 |
|
46 |
|
47 | _dispatch(buffer) {
|
48 | let end = buffer.indexOf('\0');
|
49 | if (end === -1) {
|
50 | this._pendingMessage += buffer.toString();
|
51 | return;
|
52 | }
|
53 | const message = this._pendingMessage + buffer.toString(undefined, 0, end);
|
54 | if (this.onmessage)
|
55 | this.onmessage.call(null, message);
|
56 |
|
57 | let start = end + 1;
|
58 | end = buffer.indexOf('\0', start);
|
59 | while (end !== -1) {
|
60 | if (this.onmessage)
|
61 | this.onmessage.call(null, buffer.toString(undefined, start, end));
|
62 | start = end + 1;
|
63 | end = buffer.indexOf('\0', start);
|
64 | }
|
65 | this._pendingMessage = buffer.toString(undefined, start);
|
66 | }
|
67 |
|
68 | close() {
|
69 | this._pipeWrite = null;
|
70 | helper.removeEventListeners(this._eventListeners);
|
71 | }
|
72 | }
|
73 |
|
74 | module.exports = PipeTransport;
|