开发者

custom stream object? (nodejs)

开发者 https://www.devze.com 2023-04-05 05:35 出处:网络
Is it possible to extend / initialize the require(\'stream\').Stream; object ? I would like to be able to create a stream object that i can push data to and have all the listeners notified when new da

Is it possible to extend / initialize the require('stream').Stream; object ? I would like to be able to create a stream object that i can push data to and have all the listeners notified when new data arrive.

I tried the following:

var stream = require('stream');
var test = new stream.Stream();
test.write(new Buffer('mads'));

But i get the following error:

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 (event开发者_运维技巧s.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)


For anyone who stumbles on this question today (node v0.10.x), this can be easily achieved using the PassThrough stream introduced with streams2.

var stream = require('stream');
var test = stream.PassThrough();
test.write('mads');
test.end();


You have to create those methods yourself and also set the writable property to true, and don't forget to emit the events in those methods you override as well so that you can use it as a regular event emitter. Check this question for more information.

0

精彩评论

暂无评论...
验证码 换一张
取 消