KFL
KFL

Reputation: 17850

Piping a node.js script's stdout to another's stdin doesn't work

In case you are not familiar with CoffeeScript, here's the JavaScript version of p1.coffee and p2.coffee mentioned below.

Piping a node.js script's stdout to another's stdin doesn't seem to work. I have p1.coffee which outputs numbers to stdout as fast as it can:

i = 0
(->
    i += 1
    process.stdout.write "#{i} "
    )() while true

I now have p2.coffee which does exactly what's like a cat:

process.stdin.on 'end', -> console.log "EOF"
process.stdin.pipe(process.stdout)

Now if I pipeline them together, it displays only the first number and "blocks" there:

> coffee p1.coffee | coffee p2.coffee
1 

I'm using node v0.10.31 on Windows if that matters.

Upvotes: 0

Views: 1227

Answers (1)

fardjad
fardjad

Reputation: 20404

That might be a Windows specific issue. I tried the following with Node.js v0.10.31 on OS X and it worked fine:

// cat.js

process.stdin.once('end', function () {
    console.log('EOF');
});
process.stdin.pipe(process.stdout);


// count.js

var i = 0;
while (true) {
    process.stdout.write(i++ + ' ');
}

and piped the output of count.js to cat.js:

node count.js | node cat.js

Also note that your CoffeeScript compiles to:

var i;

i = 0;

while (true) {
  (function() {
    i += 1;
    return process.stdout.write("" + i + " ");
  })();
}

Creating functions within loops makes your code slower. You could do the following instead:

i = 0
loop process.stdout.write("#{i += 1} ")

Upvotes: 2

Related Questions