'Readline infinitely while handling async console logs in Node.js

I'm trying to create a script where you can write commands:

const readline = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
})

let askCommands = async () => {
  readline.question('> ', async (command) => {
    // If user exits close readline
    if(command === 'exit') {
      readline.close();
      return process.exit();
    }
    switchCommands(command);
    askCommands();
  })
}

let switchCommands = (command) => {
  if(command === 'test') {
    setTimeout(() => {
      console.log('Hello!')
    }, 1000)
  } else {
    console.log(`Invalid command '${command}'`)
  }
}

askCommands();

It works fine until I use an async console.log(). This is because the script writes the async outputs without removing the '> ' and then generates a new line that does not have the '> '. Moreover, if in this new line you write any character and then delete it the '> ' is added automatically.

I would like to write async logs without having the '> ' before them and without removing the '> ' where users write the commands. Is there any easy solution to this problem?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source