node.js - 从标准输出读取一个问题并将响应写入标准输入
问题描述
考虑这个 bash 脚本:
# script-with-input.sh
# can't change this file :(
echo Hi
read -p "what's your name: " name
echo "That's a nice name."
read -p "what's you job: " job
echo Hello, $job $name!
我如何使用这些问题与它交流child_process.spawn
并对问题做出有意义的回答?我需要在给出回复之前得到一个问题(不能仅根据订单做出我的回复),但我的应用程序只是挂起等待输入,并且在stdout
. 我知道这与stdout
行缓冲有关,但不知道如何解决。
const child_process = require('child_process')
const cmd = 'sh script-with-input.sh'
const child = child_process.spawn(cmd, [], {shell: true})
child.stdout.on('data', data => {
console.log('data:', data.toString())
})
//child.stdin.write('John\n\metalworker\n')
function getResponse(question) { //...how do I get the question?
return question.includes('name') ? 'John' : 'metalworker'
}
解决方案
推荐阅读
- python - 查找满足条件的 xarray 索引
- google-apps-script - 我可以使用 Google Apps 脚本而不是公式在电子表格上进行计算吗?
- ssl - HTTP/2 必须使用 TLS 吗?
- json - 使用 JSON 的时间序列数据可视化
- powershell - Powershell 2.0 从 zip 中提取某些文件(包括子目录)
- javascript - 画布绘图在外部 .js 文件中不起作用
- python - 如何使用此 CFG 随机生成字符串?
- azure - 在 Azure python 烧瓶应用中安装 pymongo
- vue.js - Vue过滤重新调整数组中的所有对象,即使它们不匹配搜索条件
- java - 尽管有分隔符,为什么我的 parser.next 扫描仪仍选择括号和数字而不是 i 之前的字符串