Pipe to stdout and writeable stream

34,402

I think what you want is:

reader.pipe(catify)
catify.pipe(writer)
catify.pipe(process.stdout)

These needed to be separated because pipes return their destinations and not their source.

Share:
34,402

Related videos on Youtube

Nick Tomlin
Author by

Nick Tomlin

I sling Java and JavaScript and try to write poetry in my spare time.

Updated on July 09, 2022

Comments

  • Nick Tomlin
    Nick Tomlin almost 2 years

    I'm piping a file through a duplex string (courtesy of through) and I'm having trouble printing information to stdout and writing to the file. One or the other works just fine.

    var fs = require('fs');
    var path = require('path');
    var through = require('through'); // easy duplexing, i'm young
    
    
    catify = new through(function(data){
        this.queue(data.toString().replace(/(woof)/gi, 'meow'));
    });
    
    var reader = fs.createReadStream('dogDiary.txt'); // woof woof etc.
    var writer = fs.createWriteStream(path.normalize('generated/catDiary.txt')); // meow meow etc.
    
    // yay!
    reader.pipe(catify).pipe(writer)
    
    // blank file. T_T
    reader.pipe(catify).pipe(process.stdout).pipe(writer) 
    

    I'm assuming this is because process.stdout is a writeable stream, but I'm not sure how to do what I want (i've tried passing {end: false} to no avail).

    Still struggling to wrap my head around streams, so forgive me if i've missed something obvious : )

  • Nick Tomlin
    Nick Tomlin almost 11 years
    Thanks, this works like a charm. Any explanation on why these need to be separated like this?
  • Jonathan Ong
    Jonathan Ong almost 11 years
    pipes return their destination, not their source. and you only want to pipe into a stream once.
  • PirateApp
    PirateApp over 5 years
    upvoted! vow so the same source can actually be consumed by more than one listener without creating a new object damn! i had no idea