Home > database >  Asking for user input without pausing code / connections
Asking for user input without pausing code / connections

Time:11-26

So I'm working on a simple chat app so I can work with servers and clients, but I'm running into this issue on the client with messages not showing up, and I figured out this is because of the way I ask the user to type / send messages.

Every time that you send a message on one client, it will not show up on the other until you send another message, so I was wondering if there was another way to ask for input without disrupting the flow of receiving messages. Image of what's going on (Timestamps added for clarity)

I'm using the Prompt-Sync module.

This is the code for receiving messages, slightly slimmed down for extra readability:

const msg = prompt("> ")
if (msg.toLowerCase().split(" ")[0] == "~switch") {
   const tosw = msg.split(" ")[1]
   const valid = await axios.get("http://" server ":7072/user/" tosw)
   if (valid.data['exists']){
        ChattingWith = tosw
        console.log("you are now chatting with ??")
        prm()
        return
    } else {
        console.log("invalid username")
        prm()
        return
    }
}

socket.emit('sendmsg', msg, ChattingWith)

I tried to use multi-threading but couldn't figure out a way to integrate that with the way I was receiving messages.

I just couldn't find any modules or things on this, I know that there is probably a VERY easy fix or change I can do to achieve this but I'm slightly new with this kinda stuff so I just thought I could get some help from this community, so do you guys have any advice?

CodePudding user response:

You can achieve this with the native readline API.

Be warned it's not intuitive at all, and the docs aren't great.

Readline docs: https://nodejs.org/api/readline.html

Here's an example that will write a received message and move the user's input down one line: https://stackblitz.com/edit/node-8eprb8?file=index.js

const readline = require('readline');

const rl = readline.createInterface(process.stdin, process.stdout);

rl.setPrompt('> ');
rl.on('line', sendMsg);
rl.prompt();

function sendMsg(msg) {
  console.log('* Sending '   msg   '...');
  socket.emit('sendmsg', msg)
  rl.prompt();
}

function receiveMessage(msg) {
  const line = rl.line;
  readline.clearLine(rl, 0);
  readline.cursorTo(rl, 0);
  rl.write('# '   msg);
  rl.clearLine(1);
  rl.prompt();
  rl.write(line);
}
  • Related