how to detect if a node js script is running through a shell pipe

how to detect if a node js script is running through a shell pipe  using -'bash,node.js,pipe'

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:

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


asked Sep 18, 2015 by mca.agarwal
0 votes

3 Answers

0 votes

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');
function withoutPipe() {
   console.log('no content was piped');

var self = process.stdin;
self.on('readable', function() {
    var chunk =;
    if (chunk === null) {
    } else {
       data += chunk;
self.on('end', function() {

test with

echo "foo bar" | node test.js


node test.js
answered Sep 18, 2015 by vijaygupta1980
0 votes

I just found out a simpler answer to part of my question.

To quickly and synchronously detect if piped content is being passed to the current script in Node.js, use the process.stdin.isTTY boolean:

$ node -p -e 'process.stdin.isTTY'
$ echo 'foo' | node -p -e 'process.stdin.isTTY'

So, in a script, you could do something like this:

if (process.stdin.isTTY) {
  // handle shell arguments
} else {
  // handle piped content (see Jerome’s answer)

The reason I didn’t find this before is because I was looking at the documentation for process, where isTTY is not mentioned at all. Instead, it’s mentioned in the TTY documentation.

answered Sep 18, 2015 by sanjaypal1983
0 votes

If you need to pipe into nodejs using an inline --eval string in bash, cat works too:

$ echo "Hello" | node -e "console.log(process.argv[1]+' pipe');" "$(cat)"
# "Hello pipe"
answered Sep 18, 2015 by param.oncemore