Version 1
[yaffs-website] / node_modules / bl / node_modules / readable-stream / 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 /*<replacement>*/
9
10 var objectKeys = Object.keys || function (obj) {
11   var keys = [];
12   for (var key in obj) {
13     keys.push(key);
14   }return keys;
15 };
16 /*</replacement>*/
17
18 module.exports = Duplex;
19
20 /*<replacement>*/
21 var processNextTick = require('process-nextick-args');
22 /*</replacement>*/
23
24 /*<replacement>*/
25 var util = require('core-util-is');
26 util.inherits = require('inherits');
27 /*</replacement>*/
28
29 var Readable = require('./_stream_readable');
30 var Writable = require('./_stream_writable');
31
32 util.inherits(Duplex, Readable);
33
34 var keys = objectKeys(Writable.prototype);
35 for (var v = 0; v < keys.length; v++) {
36   var method = keys[v];
37   if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
38 }
39
40 function Duplex(options) {
41   if (!(this instanceof Duplex)) return new Duplex(options);
42
43   Readable.call(this, options);
44   Writable.call(this, options);
45
46   if (options && options.readable === false) this.readable = false;
47
48   if (options && options.writable === false) this.writable = false;
49
50   this.allowHalfOpen = true;
51   if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
52
53   this.once('end', onend);
54 }
55
56 // the no-half-open enforcer
57 function onend() {
58   // if we allow half-open state, or if the writable side ended,
59   // then we're ok.
60   if (this.allowHalfOpen || this._writableState.ended) return;
61
62   // no more data can be written.
63   // But allow more writes to happen in this tick.
64   processNextTick(onEndNT, this);
65 }
66
67 function onEndNT(self) {
68   self.end();
69 }
70
71 function forEach(xs, f) {
72   for (var i = 0, l = xs.length; i < l; i++) {
73     f(xs[i], i);
74   }
75 }