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