Search code examples
node.jsnode.js-stream

Reading lines or whole buffer from stdin (node.js)


I am developing an interactive console interface in node.js which parses and compiles input. For this purpose I am using readline.question:

require('readline').question('> ', processCommandFunction)

Now the program should also be able to read input piped to stdin from the system shell, i.e.:

$ myprog < myfile.txt

It parses the input, but with readline.question it does so line by line. That breaks some input code which spans over separate lines.

I would like change the behavior of the program so that when used interactively, it processes line by line (like it currently does) but when a file is piped to it, it should process the whole file in one chunk. So I somehow need to check whether more data is coming after a linebreak. Can someone please point me in the right direction?


Solution

  • You could check process.stdin.isTTY. If it is true, then use readline for your interactive mode. If it's not true, then just read data from process.stdin manually as a Readable stream.

    Example:

    if (process.stdin.isTTY) {
      // do readline stuff here
    } else {
      var buf = '';
      process.stdin.on('data', function(d) {
        buf += d;
      }).on('end', function() {
        // do something with buffered text in `buf`
      }).setEncoding('utf8');
    }