UNPKG

1.18 kBJavaScriptView Raw
1
2import {inherits} from 'util';
3import {nextTick} from 'process';
4import {Readable} from './readable';
5import {Writable} from './writable';
6
7inherits(Duplex, Readable);
8
9var keys = Object.keys(Writable.prototype);
10for (var v = 0; v < keys.length; v++) {
11 var method = keys[v];
12 if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
13}
14export default Duplex;
15export function Duplex(options) {
16 if (!(this instanceof Duplex)) return new Duplex(options);
17
18 Readable.call(this, options);
19 Writable.call(this, options);
20
21 if (options && options.readable === false) this.readable = false;
22
23 if (options && options.writable === false) this.writable = false;
24
25 this.allowHalfOpen = true;
26 if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
27
28 this.once('end', onend);
29}
30
31// the no-half-open enforcer
32function onend() {
33 // if we allow half-open state, or if the writable side ended,
34 // then we're ok.
35 if (this.allowHalfOpen || this._writableState.ended) return;
36
37 // no more data can be written.
38 // But allow more writes to happen in this tick.
39 nextTick(onEndNT, this);
40}
41
42function onEndNT(self) {
43 self.end();
44}