如何,如果Node.js的脚本,通过壳管运行检测? [英] How to detect if a Node.js script is running through a shell pipe?

查看:110
本文介绍了如何,如果Node.js的脚本,通过壳管运行检测?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是类似这样的:<一href=\"http://stackoverflow.com/questions/911168/detect-if-shell-script-is-running-through-a-pipe\">How如果我的shell脚本通过管道运行检测?。不同的是,我工作的shell脚本是写在Node.js的。

比方说,我输入:

 回声富酒吧| ./test.js

那么,我怎么可以得到价值 test.js

富巴

我读过 Unix和节点:管道和流但似乎只提供了一个异步解决方案(除非我错了)。我正在寻找一个解决方案同步。此外,使用这种技术,它似乎并不非常简单的检测,如果脚本被管道或没有。

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


  1. 如果一个Node.js的脚本,通过外壳管运行如何检测,例如回声富酒吧| ./test.js

  2. 如果是这样,如何​​读出的Node.js的管道价值?


解决方案

管道都是为了处理小本投入,如富巴,但也是巨大的文件。

流API可以确保您可以启动,而无需等待要通过管道完全庞大的文件数据处理(这是速度和安培好;内存)。它这样做的方法是给你的数据块。

有对管道没有同步API。如果你真的想在你的手中,整个管道输入做一些事情之前,你可以使用

注意:只能使用节点> = 0.10.0 ,因为示例使用流2 API

  VAR数据='';
功能withPipe(数据){
   的console.log('含量管道');
   的console.log(data.trim());
}
功能withoutPipe(){
   的console.log('没有内容的管道');
}VAR自= process.stdin;
self.on('读',函数(){
    变种块= this.read();
    如果(块=== NULL){
        withoutPipe();
    }其他{
       数据+ =块;
    }
});
self.on(结束,函数(){
   withPipe(数据);
});

测试以

 回声富酒吧|节点test.js

 节点test.js

My question is similar to this one: How to detect if my shell script is running through a pipe?. The difference is that the shell script I’m working on is written in Node.js.

Let’s say I enter:

echo "foo bar" | ./test.js

Then how can I get the value "foo bar" in test.js?

I’ve read Unix and Node: Pipes and Streams but that only seems to offer an asynchronous solution (unless I’m mistaken). I’m looking for a synchronous solution. Also, with this technique, it doesn’t seem very straightforward to detect if the script is being piped or not.

TL;DR My question is two-fold:

  1. How to detect if a Node.js script is running through a shell pipe, e.g. echo "foo bar" | ./test.js?
  2. If so, how to read out the piped value in Node.js?

解决方案

Pipes are made to handle small inputs like "foo bar" but also huge files.

The stream API makes sure that you can start handling data without waiting for the huge file to be totally piped through (this is better for speed & memory). The way it does this is by giving you chunks of data.

There is no synchronous API for pipes. If you really want to have the whole piped input in your hands before doing something, you can use

note: use only node >= 0.10.0 because the example uses the 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);
});

test with

echo "foo bar" | node test.js

and

node test.js

这篇关于如何,如果Node.js的脚本,通过壳管运行检测?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆