bash – 如何检测Node.js脚本是否通过shell管道运行?
发布时间:2020-12-15 19:17:59 所属栏目:安全 来源:网络整理
导读:我的问题类似于这一个: 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: Pipe
我的问题类似于这一个:
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?
管道用于处理像“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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |