I like to check if there is any data in stdin and if there isn't to move on. When I write this code
process.stdin.on 'data', (d) ->
console.log 'data ' + d.length + " " + d
process.stdin.on 'end', () ->
console.log 'end'
It blocks and allows me to type into my console. I don't want that. I really only want to know if data was piped in (such as echo 'data' |
) and if not ignore stdin. How do I check if there is data in stdin without blocking?
Unfortunately, it does not look like there is a good way to do this in node. If no stream is piped in at all, node will wait for input from the terminal, which is not what we want in this case. However, /dev/null
can be used to trigger the end
event, without passing in any data.
The workaround I have been using is to have a shell script that executes my node script like so:
#!/usr/bin/env bash
if [ -t 0 ]; then
exec ./index.js < /dev/null
else
exec ./index.js
fi
This works because node will send the end
event when /dev/null
is used as the stdin. This script checks if a stdin stream exists at all, and then sends either /dev/null
or the original stream.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With