实现双工流


【Implementing a duplex stream】

一个 Duplex 流是同时实现了 ReadableWritable 的流,例如 TCP 套接字连接。

【A Duplex stream is one that implements both Readable and Writable, such as a TCP socket connection.】

由于 JavaScript 不支持多重继承,stream.Duplex 类被扩展以实现 Duplex 流(而不是同时扩展 stream.Readablestream.Writable 类)。

【Because JavaScript does not have support for multiple inheritance, the stream.Duplex class is extended to implement a Duplex stream (as opposed to extending the stream.Readable and stream.Writable classes).】

stream.Duplex 类从原型上继承自 stream.Readable,并以寄生方式继承自 stream.Writable,但由于在 stream.Writable 上重写了 Symbol.hasInstanceinstanceof 对两个基类都能正常工作。

【The stream.Duplex class prototypically inherits from stream.Readable and parasitically from stream.Writable, but instanceof will work properly for both base classes due to overriding Symbol.hasInstance on stream.Writable.】

自定义 Duplex 流必须调用 new stream.Duplex([options]) 构造函数,并实现 readable._read()writable._write() 方法。

【Custom Duplex streams must call the new stream.Duplex([options]) constructor and implement both the readable._read() and writable._write() methods.】