2

I have a setInterval who logs the time every second. I want to use STDIN to execute commands in my script, but the STDOUT is moving the cursor while I'm typing and puts itself in the prompt.

I don't have much experience with prompts, just started diving into this.

Script:

setInterval(function(){
    console.log(new Date().toUTCString());
},1000)

var readline = require('readline');

var rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

rl.question("Hi there, how are you?", function(answer) {

});

Output:

Hi there, how are you?Mon, 17 Dec 2012 16:20:34 GMT
fine
Mon, 17 Dec 2012 16:20:35 GMT
Mon, 17 Dec 2012 16:20:36 GMT
Mon, 17 Dec 2012 16:20:37 GMT
Mon, 17 Dec 2012 16:20:38 GMT

How would you solve something like this? Cache all the STDOUT, clear the screen, write all the STDOUT and prompt again every time console.log() is logging?

Yes I do want to create some kind of chat based system/command line interface where the output stays above the input.

Thanks!

Brmm
  • 320
  • 1
  • 2
  • 11
  • Why do you want to simultaneously be logging to stdout and typing? Maybe log to a file instead? Your input should still work even if it is spread across a few lines visually. – loganfsmyth Dec 17 '12 at 16:35
  • 2
    Lets say I want to create some kind of chat client that works in the terminal, I dont necessary want to log my input, but there is logging going on because of other factors (like other users for example) – Brmm Dec 17 '12 at 16:39

1 Answers1

3

Basically what you are asking is how to make a complex terminal application. The most popular library for this is called ncurses and it has node bindings here. I don't have personal experience using it unfortunately.

Your other option would be to do as your said, and manually re-render the terminal using your own internal buffers. You can get the size of the output terminal using Node's tty module, docs here, and then use ANSI escape codes to clear the terminal, position the cursor where you want, and then use process.stdout.write to print what you want.

You can see an example of using escape codes in my other question over here

Community
  • 1
  • 1
loganfsmyth
  • 156,129
  • 30
  • 331
  • 251
  • Thanks for your advice, so I guess that's the way to do it then. Do you think re-rendering the terminal is also the technique being used in other complex terminal applications like the Eggdrop partyline via telnet for example? – Brmm Dec 17 '12 at 18:28