Skip to content

Detect if node receives stdin

I’m interested in determining if my node script is being called with data being streamed into it or not.

That is, I want to differentiate between these two cases

$ node index.js
$ ls | node index.js

I found this way of determining that:

if(process.stdin.isTTY) {
  console.log('called without pipe');
} else {
  console.log('called with data streamed in');
}

Is it reliable? Is it semantically appropriate?

Answer

Answering my own question: here’s a link to the [docs].

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