Express GET:使用Spawn运行Python,使用fs读取文件并发送响应会产生延迟的结果

问题描述 投票:0回答:1

我在Express中使用GET来运行以下命令

app.get('/get_temp_hum', function(req, res) {
        var process = spawn('python',["ECIES_decotp.py"]);
        process.stdout.on('data', function(data) {
            console.log(data.toString());
        } )
        process.stderr.on('data', function(data) {
            console.log(data.toString());
        } )
        process.stderr.on('exit', function(code) {
            console.log('Exited with code' + code);
        } )
        fs.readFile('c.json', 'utf8', function (err, data) {
                if (err) throw err;
                //console.log(data);
                temp_hum_json = data;
            })
        res.send(temp_hum_json);
});

而且我叫那个GET的URL,所以我可以让它显示res.send(temp_hum_json)的值

但是由于某种原因,我第一次调用它,它显示的是空白页面,并且仅在我再次调用结果后才会显示结果。当我用Postman打电话时,同样的事情也会发生。每当我启动服务器时都会发生这种情况。这是有问题的,因为我需要显示的值具有一致性,以便可以将URL放在服务器上。它可能与异步命令有关,我该如何解决?

node.js express fs spawn
1个回答
0
投票

生成进程以及NodeJS中的readFile也是异步执行的,这就是为什么。如果要获得一致的结果,则需要使用回调。当您跨进程时,可以使用

从该进程实时获取数据。
process.stdout.on("data", data => {
  //do whatever you want with data here
})

[如果python进程为您提供了一个json文件,并且您需要读取该文件,则应在完成执行后,以python进程发送的退出代码0读取它

 process.stderr.on('exit', function(code) {
       if(code ===0){
         fs.readFile('c.json', 'utf8', function (err, data) {
                    if (err) throw err;
                    //console.log(data);
                    temp_hum_json = data;
                })
            res.send(temp_hum_json);
        }
      })

最终代码必须是这样的:

app.get('/get_temp_hum', function(req, res) {
        var process = spawn('python',["ECIES_decotp.py"]);
        process.stdout.on('data', function(data) {
            // do whatever you want here with stream data from python process 
            console.log(data.toString());
        } )
        process.stderr.on('data', function(data) {
            console.log(data.toString());
        } )
        process.stderr.on('exit', function(code) {
            if(code === 0){
             fs.readFile('c.json', 'utf8', function (err, data) {
                if (err) throw err;
                //console.log(data);
                temp_hum_json = data;
            })
        res.send(temp_hum_json);
         } 
        } )
});
© www.soinside.com 2019 - 2024. All rights reserved.