简体   繁体   English

如何检测Node的process.stdout是否正在通过管道传输?

[英]How to detect if Node's process.stdout is being piped?

Is there any way I can detect if the output from my Node.js script is being piped to something other then the terminal? 有什么方法可以检测我的Node.js脚本的输出是否被管道传输到终端以外的其他东西?

I would like some way of detecting if this is happening: 我想要一些方法来检测是否发生这种情况:

node myscript.js | less

Or if this is happening: 或者如果发生这种情况:

node myscript.js

The easiest way would be process.stdout.isTTY (0.8 +): 最简单的方法是process.stdout.isTTY (0.8 +):

$ node -p -e "Boolean(process.stdout.isTTY)"
true
$ node -p -e "Boolean(process.stdout.isTTY)" | cat
false

(example from the official documentation) (来自官方文档的例子)

Alternatively you can use the tty module for finer grained control: 或者,您可以使用tty模块进行更精细的控制:

if (require('tty').isatty(1)) {
    // terminal
}

you can check whether stdout of running process is piped by looking where its file descriptor points, for example like below 您可以通过查看其文件描述符指向的位置来检查运行进程的stdout是否通过管道传输,例如如下所示

readlink /proc/<your process id>/fd/1

or, more specifically 或者,更具体地说

[[ $(readlink /proc/$(pgrep -f 'node myscript.js')/fd/1) =~ ^pipe ]] && echo piped

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM