简体   繁体   中英

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!

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM