在节点js中调用python脚本=> ERR_HTTP_HEADERS_SENT

时间:2020-03-27 09:54:46

标签: python node.js

我在其中调用python脚本的i节点js项目。问题在于它仅显示输出的一部分,服务器掉落并显示错误ERR_HTTP_HEADERS_SENT。

hello.py

import sys
for i in range(3000):
    print(i)
sys.stdout.flush()

index.js

const express = require('express')
const app = express()
const bodyParser = require('body-parser')


app.set('view engine', 'ejs')
app.use(bodyParser.urlencoded({ limit: '10mb', extended: false }))

app.get("/", (req, res) => {
    const spawn = require("child_process").spawn
    const pythonProcess = spawn('python', ["./hello.py"])
    pythonProcess.stdout.on('data', (data) => {
        results = data.toString().split("\r\n")
        res.render("../index.ejs", {results})
    })
})

app.listen(process.env.PORT || 3000)

index.ejs

<h2>Results:</h2>
<% results.forEach(result => { %>
    <div><%= result %> </div>
<% }) %>

结果是页面的编号从0到1550,每个页面都位于单独的行中,但是它应该是0到3000,这是怎么回事?

1 个答案:

答案 0 :(得分:1)

发生这种情况是由于data实际上是一个,它的输出被逐段读取为数据块,这意味着侦听器on('data',..正在触发不止一次;每次收到一个块。

要获得全部结果,我们必须等到所有零件都收到后,这才是

router.get('/', (req, res) => {
  const pythonProcess = spawn('python', ['./hello.py']);
  let result = [];

  // this listener will keep triggering until all chunks are received
  pythonProcess.stdout.on('data', data => {
    result = result.concat(data.toString().split('\r\n'));
  });
  // on.exit() will indicate that process has finished
  pythonProcess.on('exit', code => {
    console.log(`process has finished and exited with code: ${code}`);
    res.render('../index.ejs', { result });
  });
});

希望我有所帮助