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

后端 未结 1 389
悲&欢浪女
悲&欢浪女 2021-01-31 02:25

I see how to pipe stuff together using Node.js streams, but how do you pipe multiple scripts together using the Unix |, given that some of these scripts can be asyn

1条回答
  •  一整个雨季
    2021-01-31 02:49

    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.

    0 讨论(0)
提交回复
热议问题