首页 > 解决方案 > 节点流结束:结束后写入

问题描述

在此处输入图像描述

当我将输入发送到用 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 代码来接受输入进行计算并将结果传递给我。

标签: javascriptpythonnode.js

解决方案


您将在第一次调用后完全结束输入流。进入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]而不是将对象转换为字符串并解析字符串。


推荐阅读