Pipe to stdout and writeable stream

Nick Tomlin picture Nick Tomlin · Jul 24, 2013 · Viewed 32.4k times · Source

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 : )

Answer

Jonathan Ong picture Jonathan Ong · Jul 24, 2013

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.