node.jspipejsonstream

Using Writable stream as an event emitter


I am wondering if it is possible to use a writable stream (require('stream').Writable) as an event emitter.

For example,

   var jsonData = [];

   var strm = new stream.Writable({
        write: function(chunk, encoding, next) {

            jsonData.push(chunk.toString());
            next();
        }

    });


    strm.on('foo',function(msg){
        console.log(msg); //doesn't get called
    });

    strm.emit('foo','bar');  //this doesn't seem to do anything

I thought that Readable/Writable streams were event-emitters, but it doesn't seem I can really use them this way? Also wondering if I am using Writable correctly by writing to an array outside of the Writable object/stream.


Solution

  • Streams indeed event-emitters, your code sample works perfectly fine on node v4.2.4

    vladmiller:tmp vladmiller$ node test.js
    bar
    

    and node v0.12.7

    vladmiller:tmp vladmiller$ node test.js
    bar