Sunday, 20 November 2022

node.js readline (or similar) tool to manage input

I am using readline to manage a program that will have events emitted to it from a websocket connection. The problem I have is that when messages are emitted to stdout, the formatting of the tty is broken in that the input line doesn't stay at the bottom of the screen. Here's example code:

const WebSocket = require("ws");
const readline = require("readline");

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

function getInput() {
  rl.question("SEND> ", function (answer) {
    if (answer.trim() === "quit") {
      rl.close();
      ws.close();
      process.exit();
    } else {
      ws.send(answer);
    }
  });
}

const ws = new WebSocket("wss://websocket-echo.com/");

ws.on("open", function open() {
  console.log("connected -- begin sending nonsense to console");
  setInterval(() => {
    console.log(` SPAM: ${(Math.random() + 1).toString()}`);
    readline.cursorTo(process.stdout, 0);
  }, 5000);
  getInput();
});

ws.on("close", function close() {
  console.log("disconnected");
});

ws.on("message", function message(data) {
  readline.cursorTo(process.stdout, 0);
  console.log(`RECV> ${data}`);
  getInput();
});

The output overwrites the input line. I was hoping there is a library that helps manage this so that output stays above the input line. Are there any tools that can facilitate this behavior? Ultimately I am looking for a better prompt interface when a new line is added to stdout.



from node.js readline (or similar) tool to manage input

No comments:

Post a Comment