Node.js Pipe – Determine if Process is Connected to Another via Pipes

node.jspipe

If I do this:

x | y

is there any way to check, during the runtime of x, to see if it's connected to y? Note that I don't know what y is, and I am not responsible for starting y.

Specifically, I am talking about the Node.js runtime, so perhaps this is a Node.js specific question. But ultimately, I am wondering if it's possible to determine given any runtime. Is it possible and how?

Is it possible to determine if the stdout/stderr are hooked up to the stdin of another process? I guess that's what this question is about.

Best Answer

To check whether the program's output is going to a pipe, based on https://nodejs.org/api/fs.html#fs_class_fs_stats, you want to call fs.fstat(FileDescriptor) and then call isFIFO() on the returned stat object (FIFO == first-in-first-out == a pipe or a named pipe):

$ </dev/null node -e 'var fs=require("fs");
   fs.fstat(0,function(err,stats){ if(err) throw(err); console.log(stats.isFIFO()); });  ' 
  false
$  : | node -e 'var fs=require("fs");
   fs.fstat(0,function(err,stats){ if(err) throw(err); console.log(stats.isFIFO()); });  ' 
  true

In C, you'd make the fstat syscall and then test the .st_mode field of the returned struct stat using the S_ISFIFO macro.

If you like to waste CPU cycles and want to use an external binary, you can execute test -p /dev/fd/$THE_FD to get the answer (or invoke that in a shell where test will be a builtin, or run stat, or launch something else capable of determining the file type).

Related Question