javascript - 节点流结束:结束后写入
问题描述
当我将输入发送到用 python 编写的子进程时,我遇到了错误。当我第一次发送数据时,它会给出输出,但在第二次输入时,我会向我发送错误。提示覆盖的管道在我收到第一个输出之后结束。你能帮助我吗。
这是节点代码。
var bodyParse = require('body-parser');
var urlencodedParser = bodyParse.urlencoded({extended: false});
var spawn = require('child_process').spawn
var py = spawn('python', ['dialogue_management_model.py'])
module.exports = function(app) {
app.get('/', function(req, res) {
res.render('index');
});
app.post('/', urlencodedParser, function(req, res) {
var typed = (JSON.stringify(req.body).substring(2, JSON.stringify(req.body).indexOf(":") - 1));
console.log(typed)
module.exports.typed = typed
var data = typed;
dataString = '';
// Handling the Input data from the Front End With the Post request.
// taking computed/operated data from the python file
py.stdout.on('data', function(data){
dataString += data.toString();
});
// Simply logging it to the Console
py.stdout.on('end', function(){
console.log(dataString);
res.send(dataString);
});
// python doesn't understand the data without string format
py.stdin.write(data);
py.stdin.end();
})
}
Just Server 在其他文件中启动,并将完全控制权传递给这里,从这里我调用 python 代码来接受输入进行计算并将结果传递给我。
解决方案
您将在第一次调用后完全结束输入流。进入postvar py = spawn('python', ['dialogue_management_model.py'])
请求处理程序,因此每个请求都会产生一个子进程,写入数据,结束输入流,等待响应,并在输出流结束时返回结果。
这为您提供了使其更线程安全的额外好处。也就是说,如果你有两个请求同时进来,最终都会添加监听器py.stdout.on('data', ...
,导致两者都得到混合输出。此外,我相当肯定py.stdout.on('end',
只会触发一次,因此在 stdout.end 回调从第一个请求运行之后进入的任何请求都会挂起,直到它们超时。
此外,与您的问题无关,但是当您这样做时:
var typed = (JSON.stringify(req.body).substring(2, JSON.stringify(req.body).indexOf(":") - 1))
您应该将其分配JSON.stringify()
给一个变量,这样您就不必运行它两次。
IE。var payload = JSON.stringify(req.body); var typed = (payload.substring(2, payload.indexOf(":") - 1))
但即便如此,如果您只需要第一个键,您就可以这样做,Object.keys(req.body)[0]
而不是将对象转换为字符串并解析字符串。
推荐阅读
- r - 使用 R (CRAN) 在多列中以特定模式分隔
- angular - Angular 单元测试 - 使用两个 beforeEach() 方法(一个同步和一个异步),它们是否总是以正确的顺序执行/解决?
- node.js - 在 HTTP 请求中解析 JSON 中的图像
- r - 在 ggplot 组合中绘制 gamma、normal 和 t 的 PDF
- postgresql - 在 PostgreSQL 中将 varchar(255) 类型的列转换为 date 类型
- scala - Scala,ZIO - 如果数据未插入 cassandra 数据库,则重试
- python - Seaborn 和 Matplotlib xaxis 标签和行为
- node.js - 如果我使用 express 生成器模板,是否需要指定生产构建命令?
- python - 以印度/美国表示法转换数字以值的变化结束
- android - 为什么从活动传递到广播接收器时字符串值为空?