doc: improvements to debugger.markdown copy
[platform/upstream/nodejs.git] / lib / _stream_duplex.js
1 // a duplex stream is just a stream that is both readable and writable.
2 // Since JS doesn't have multiple prototypal inheritance, this class
3 // prototypally inherits from Readable, and then parasitically from
4 // Writable.
5
6 'use strict';
7
8 module.exports = Duplex;
9
10 const util = require('util');
11 const Readable = require('_stream_readable');
12 const Writable = require('_stream_writable');
13
14 util.inherits(Duplex, Readable);
15
16 var keys = Object.keys(Writable.prototype);
17 for (var v = 0; v < keys.length; v++) {
18   var method = keys[v];
19   if (!Duplex.prototype[method])
20     Duplex.prototype[method] = Writable.prototype[method];
21 }
22
23 function Duplex(options) {
24   if (!(this instanceof Duplex))
25     return new Duplex(options);
26
27   Readable.call(this, options);
28   Writable.call(this, options);
29
30   if (options && options.readable === false)
31     this.readable = false;
32
33   if (options && options.writable === false)
34     this.writable = false;
35
36   this.allowHalfOpen = true;
37   if (options && options.allowHalfOpen === false)
38     this.allowHalfOpen = false;
39
40   this.once('end', onend);
41 }
42
43 // the no-half-open enforcer
44 function onend() {
45   // if we allow half-open state, or if the writable side ended,
46   // then we're ok.
47   if (this.allowHalfOpen || this._writableState.ended)
48     return;
49
50   // no more data can be written.
51   // But allow more writes to happen in this tick.
52   process.nextTick(onEndNT, this);
53 }
54
55 function onEndNT(self) {
56   self.end();
57 }