[英]How to get realtime spawned childProcess.stdout in node.js
I am using Node to call a command which sometimes returns an interactive shell prompt.我正在使用 Node 调用有时会返回交互式 shell 提示的命令。 And I'm using
ChildProcess.spawn
to create the subprocess.我正在使用
ChildProcess.spawn
创建子流程。
Here's my node.js code:这是我的 node.js 代码:
let ps = ChildProcess.spawn('command', ['arg1', 'arg2'], { interactive: true })
ps.stdout.on('data', data => {
console.log('GOT SOME DATA:', data.toString())
})
ps.stderr.on('data', data => {
console.log('ERROR:', data.toString())
})
And my script sometimes has an interactive prompt like:我的脚本有时会出现如下交互式提示:
Enter Password:
I would like to be able to listen for this text (something like if (line.match(/^Enter Password:/)) { ... }
, and then write to stdin , but ps.stdout.on('data', ...)
doesn't get called until the process exits.我希望能够收听此文本(类似于
if (line.match(/^Enter Password:/)) { ... }
,然后写入stdin ,但是ps.stdout.on('data', ...)
在进程退出之前不会被调用。
How do I flush the process's stdout stream and get the data right away (or even poll for it)?我如何刷新进程的标准输出流并立即获取数据(甚至轮询它)?
Note: I've also tried pty.js
and no luck, it seems to just completely stall.注意:我也试过
pty.js
没有运气,它似乎完全停止了。
Your code is working fine , I was just receiving a buffer and not a string , try with string interpolation :您的代码工作正常,我只是收到一个缓冲区而不是字符串,请尝试使用字符串插值:
let ps = ChildProcess.spawn('ls', [], { interactive: true})
ps.stdout.on('data', data => {
console.log(`Got some data : ${data}`)
})
ps.stderr.on('data', data => {
console.log(`Got some error : ${data}`)
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.