我知道如何使用Node.js streams将内容串联在一起,但是如果要使用Unix的 |
符号将多个脚本串联在一起,该怎么办?特别是因为其中一些脚本是异步的。
$ ./a.js | ./b.js
示例:
a.js(权限为 0755)
#!/usr/bin/env node
setTimeout(function(){
console.log(JSON.stringify({ foo: 'bar' }));
}, 10);
b.js (文件权限为 0755)
#!/usr/bin/env node
console.log(process.argv);
这是输出结果:
$ ./a.js | ./b.js
[ 'node', '/Users/viatropos/tests/b.js' ]
events.js:72
throw er; // Unhandled 'error' event
^
Error: write EPIPE
at errnoException (net.js:883:11)
at Object.afterWrite (net.js:700:19)
乍一看似乎有很多问题,不确定从哪里开始。有没有办法让这个工作?最终目标是能够获取./a.js
的console.log
输出并在./b.js
中使用它。原因是大多数情况下这些脚本将逐个运行,但有时可以将它们组合在一起,因此理想情况下系统应该能够处理这两种情况。