bash – 如何检测Node.js脚本是否通过shell管道运行?

我的问题类似于这一个: How to detect if my shell script is running through a pipe?.不同的是,我正在处理的shell脚本是写在Node.js.

假设我输入:

echo "foo bar" | ./test.js

那么如何在test.js中获取值“foo bar”?

我已经阅读了Unix and Node: Pipes and Streams,但这似乎只是提供一个异步解决方案(除非我是错误的)。我正在寻找同步解决方案。此外,使用这种技术,检测脚本是否被管道似乎并不直接。

TL; DR我的问题是双重的:

>如何检测Node.js脚本是否通过shell管道运行,例如echo“foo bar”| ./test.js?
>如果是这样,如何读取Node.js中的管道值?

管道用于处理像“foo bar”这样的小输入,但是也是巨大的文件。

流API确保您可以开始处理数据,而无需等待巨大的文件被完全管道通过(这对于速度和内存更好)。它的做法是给你大量的数据。

没有管道的同步API。如果您在做某事之前真的想要将全部管道输入输入您的手中,可以使用

注意:仅使用node >= 0.10.0,因为该示例使用stream2 API

var data = '';
function withPipe(data) {
   console.log('content was piped');
   console.log(data.trim());
}
function withoutPipe() {
   console.log('no content was piped');
}

var self = process.stdin;
self.on('readable',function() {
    var chunk = this.read();
    if (chunk === null) {
        withoutPipe();
    } else {
       data += chunk;
    }
});
self.on('end',function() {
   withPipe(data);
});

测试与

echo "foo bar" | node test.js

node test.js

相关文章

用的openwrt路由器,家里宽带申请了动态公网ip,为了方便把2...
#!/bin/bashcommand1&command2&wait从Shell脚本并行...
1.先查出MAMP下面集成的PHP版本cd/Applications/MAMP/bin/ph...
1、先输入locale-a,查看一下现在已安装的语言2、若不存在如...
BashPerlTclsyntaxdiff1.进制数表示Languagebinaryoctalhexa...
正常安装了k8s后,使用kubect工具后接的命令不能直接tab补全...