UNPKG

2.16 kBJavaScriptView Raw
1// Copyright © 2018 IBM Corp. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14'use strict';
15
16const stream = require('stream');
17
18class PassThroughDuplex extends stream.Duplex {
19 constructor(options) {
20 super(options);
21
22 this.destinations = [];
23
24 this.passThroughReadable = new stream.PassThrough();
25 this.passThroughReadable.on('error', function(error) {
26 this.emit(error);
27 });
28
29 this.passThroughWritable = new stream.PassThrough();
30 this.passThroughWritable.on('error', function(error) {
31 this.emit(error);
32 });
33 }
34
35 // readable
36
37 pipe(destination, options) {
38 this.destinations.push(destination);
39 return this.passThroughReadable.pipe(destination, options);
40 }
41
42 read(size) {
43 return this.passThroughReadable.read(size);
44 }
45
46 setEncoding(encoding) {
47 return this.passThroughReadable.setEncoding(encoding);
48 }
49
50 // writable
51
52 end(chunk, encoding, callback) {
53 return this.passThroughWritable.end(chunk, encoding, callback);
54 }
55
56 write(chunk, encoding, callback) {
57 return this.passThroughWritable.write(chunk, encoding, callback);
58 }
59
60 // destroy
61
62 destroy(error) {
63 this.passThroughWritable.destroy(error);
64 this.passThroughReadable.destroy(error);
65 }
66
67 // events
68
69 on(event, listener) {
70 if (!this.passThroughWritable) {
71 return super.on(event, listener);
72 }
73
74 switch (event) {
75 case 'drain':
76 case 'finish':
77 return this.passThroughWritable.on(event, listener);
78 default:
79 return super.on(event, listener);
80 }
81 }
82}
83
84PassThroughDuplex.addListener = PassThroughDuplex.on;
85
86module.exports = PassThroughDuplex;