1

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?

1 Answer 1

4

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');
}
Sign up to request clarification or add additional context in comments.

2 Comments

Sounds good... but I just thought about what would happen if the user pastes a multi-line block of code into the console. Can I check if more incoming data is queued after the newline?
Is it javascript code or ? If it's javascript, why not use a REPL instead?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.