3

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?

  • You're solving the problem the wrong way. Does this answer your question: http://stackoverflow.com/questions/7080458/test-whether-the-actual-output-is-a-terminal-or-not-in-node-js ? If it does I'll close this as a duplicate to that. – slebetman Aug 11 '16 at 06:14

1 Answers1

1

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.

njenan
  • 83
  • 1
  • 7