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'
true
$ echo 'foo' | node -p -e 'process.stdin.isTTY'
undefined
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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…