是否可以扩展/初始化require('stream')。对象?我希望能够创建一个流对象,我可以将数据推送到新对象并通知所有侦听器。
我尝试了以下内容:
var stream = require('stream');
var test = new stream.Stream();
test.write(new Buffer('mads'));
但我收到以下错误:
TypeError: Object [object Object] has no method 'write'
at repl:1:6
at Interface.<anonymous> (repl.js:168:22)
at Interface.emit (events.js:67:17)
at Interface._onLine (readline.js:153:10)
at Interface._line (readline.js:408:8)
at Interface._ttyWrite (readline.js:585:14)
at ReadStream.<anonymous> (readline.js:73:12)
at ReadStream.emit (events.js:88:20)
at ReadStream._emitKey (tty_posix.js:306:10)
at ReadStream.onData (tty_posix.js:69:12)
at ReadStream.emit (events.js:67:17)
答案 0 :(得分:13)
对于今天偶然发现此问题的任何人(节点v0.10.x),可以使用streams2引入的PassThrough流轻松实现这一点。
var stream = require('stream');
var test = stream.PassThrough();
test.write('mads');
test.end();
答案 1 :(得分:2)
您必须自己创建这些方法并将writable
属性设置为true,并且不要忘记emit
您重写的那些方法中的事件,以便您可以将其用作常规事件发射器。查看this question了解详情。