How to pipe Node.js scripts together using the Unix | pipe (on the command line)?

三世轮回 提交于 2019-12-02 17:26:45
Aaron Dufour

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.loging.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!