How to pipe Node.js scripts together using the Unix | pipe (on the command line)?
Solution 1:
The problem is that your b.js
immediately ends and closes its standard in, which causes an error in a.js
, because its standard out got shut off and you didn't handle that possibility. You have two options: handle stdout closing in a.js
or accept input in b.js
.
Fixing a.js
:
process.on("SIGPIPE", process.exit);
If you add that line, it'll just give up when there's no one reading its output anymore. There are probably better things to do on SIGPIPE depending on what your program is doing, but the key is to stop console.log
ing.
Fixing b.js
:
#!/usr/bin/env node
var stdin = process.openStdin();
var data = "";
stdin.on('data', function(chunk) {
data += chunk;
});
stdin.on('end', function() {
console.log("DATA:\n" + data + "\nEND DATA");
});
Of course, you don't have to do anything with that data. They key is to have something that keeps the process running; if you're piping to it, stdin.on('data', fx)
seems like a useful thing to do.
Remember, either one of those will prevent that error. I expect the second to be most useful if you're planning on piping between programs.