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

前端之家收集整理的这篇文章主要介绍了bash – 如何检测Node.js脚本是否通过shell管道运行?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我的问题类似于这一个: How to detect if my shell script is running through a pipe?.不同的是,我正在处理的shell脚本是写在Node.js.

假设我输入:

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

  1. var data = '';
  2. function withPipe(data) {
  3. console.log('content was piped');
  4. console.log(data.trim());
  5. }
  6. function withoutPipe() {
  7. console.log('no content was piped');
  8. }
  9.  
  10. var self = process.stdin;
  11. self.on('readable',function() {
  12. var chunk = this.read();
  13. if (chunk === null) {
  14. withoutPipe();
  15. } else {
  16. data += chunk;
  17. }
  18. });
  19. self.on('end',function() {
  20. withPipe(data);
  21. });

测试与

  1. echo "foo bar" | node test.js

  1. node test.js

猜你在找的Bash相关文章