Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simultaneously input and output in NodeJS

So I'm trying to make a script in NodeJS that can take output from a spawned child process and print it to the console, and take input from the user and send it to the child process and press enter. I currently have this setup:

function log(data) {
  process.stdout.write(data.toString())
}

childProcess.stdout.on('data', log)
childProcess.stderr.on('data', log)

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

rl.question("Command>> ", cmd => {
  childProcess.stdin.write(cmd + '\n')
})

But if I don't give it an answer by the time the child process gives its first output, it logs where my cursor is: on the question. I would also like it to keep the input prompt at the bottom if possible, but it's not too important.

How would I go about doing this? All help appreciated, thanks!

like image 433
BlockyPenguin Avatar asked May 21 '26 12:05

BlockyPenguin


1 Answers

So, thanks to the comment from @Bergi, I had a closer look at readline, and found a different approach to it. Here's what I did:

function log(data) {
  readline.cursorTo(process.stdout, 0, process.stdout.rows + 1)
  process.stdout.write(data.toString())
}

childProcess.stdout.on('data', log)
childProcess.stderr.on('data', log)

let rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  prompt: ''
})

rl.on('line', (line) => {
  childProcess.stdin.write(line.trim() + '\n')
  rl.prompt()
})

I'll admit, it's not the best, but it's all I need :) Thanks Bergi!

like image 124
BlockyPenguin Avatar answered May 24 '26 02:05

BlockyPenguin