Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent input/output mixing in Node.js console?

I just managed to to get a Node.js minecraft bot API (called mineflayer) to work. When I was making minecraft bot the last time (in C++, all by myself), I had a problem that when writing in the console, the server messages would mix with whatever I'm writing. The answers I got back then seemed to have too complicated/unclear solutions so I gave up.

Now I was hoping that Node.js has this problem solved, but apparently not. Is there an easy solution in Node.js? What I want is this:

image description

But now, commands that I'm writing mix with output (red is written input, green is console output, colored using GIMP):

image description

I am using the readline module for that:

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

rl.on('line', function(line) {
  var inp = line.trim();
  //Bot internal commands start with ~
  if(line[0]=='~') {
    command(line.substr(1));
  }
  else {
    //use server chat
    bot.chat(line);
  }
});
like image 361
Tomáš Zato - Reinstate Monica Avatar asked Mar 06 '26 04:03

Tomáš Zato - Reinstate Monica


1 Answers

I'm starting with a simple functional example just to show you a way to do it:

var
    readline = require("readline"),
    ansi = require('ansi');

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

ansi.clear();
ansi.row(1);

rl.on('line', function(line) {

    ansi.row(2);
    ansi.clearLine();
    ansi.print(line);

    ansi.row(1);
    ansi.clearLine();
});

The library ansi is a simple test I've made months ago to manipulate terminal lines using ANSI escape codes. To use it, simply run the following command in the same folder as the code above:

npm install https://github.com/luciopaiva/ansi.git

You can check my code by going directly to my library's repository.

The code is very simple and I recommend that you copy it and adapt to your needs.

ansi.clear() just clears the whole terminal, then ansi.row(1) moves the cursor to the first row, where you will be able to input commands. In my simple example, the code will just print to row #2 what the user typed before hitting the return key. Then just run the code above to see it working and adapt it to a mechanism that rolls the messages along the remaining lines of the terminal.

like image 119
Lucio Paiva Avatar answered Mar 08 '26 17:03

Lucio Paiva