Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pipe to stdout and writeable stream

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

like image 856
Nick Tomlin Avatar asked Jul 23 '13 22:07

Nick Tomlin


People also ask

What is the correct way to pipe a readable stream and a writable stream?

To consume a readable stream, we can use the pipe / unpipe methods, or the read / unshift / resume methods. To consume a writable stream, we can make it the destination of pipe / unpipe , or just write to it with the write method and call the end method when we're done.

What is a stream pipe?

A stream pipe is a UNIX interprocess communication (IPC) facility that allows processes on the same computer to communicate with each other.

What does .pipe do in node JS?

pipe() method in a Readable Stream is used to attach a Writable stream to the readable stream so that it consequently switches into flowing mode and then pushes all the data that it has to the attached Writable.


1 Answers

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.

like image 97
Jonathan Ong Avatar answered Sep 30 '22 23:09

Jonathan Ong