首页 > 解决方案 > 如何在 node.js 中等待响应,直到 child_process 完成?

问题描述

我想从 vuejs 向 node.js 服务器发出 axios 请求。此请求会触发服务器上的 python 脚本,该脚本会创建一个文件,该文件必须作为文件下载发送回用户。

编辑:代码实际上很好。这显然是一些服务器问题。为了完整起见,我将粘贴代码片段。

我有以下 prime-vue 组件可以将文件上传到服务器..

<FileUpload name="upFile" url="http://localhost:3000/upload" :multiple="false" @upload="processFile"  :maxFileSize="10000000">

这是文件上传后调用的函数。如果 promise 得到满足,则正在下载返回的文件。代码来自这篇文章

axios.get("http://localhost:3000/single-file", {
        params: {
          filename: event.files[0].name
        },
        responseType: 'arraybuffer'
      })
.then(function (response) {
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', response.config.params.filename.replace('zip', 'docx'));
        document.body.appendChild(link);
        link.click();
      })

在节点中,文件上传正在由 /upload 路由处理并移动文件..

app.post('/upload', type, upload.array(), cors(), jsonParser, (req, res) => {
    fs.copyFile(req.file.path, '/home/ubuntu/bot/input/' + req.file.originalname, (err) => {
      if (err) throw err;
    });
    res.send("OK");
});

/single-file 路由处理其余部分,例如调用 python 脚本并返回一个文件..

app.get('/single-file', type, upload.array(), cors(), jsonParser, (req, res) => {

    var filename = req.query.filename;
    
    const spawn = require("child_process").spawn;
    const pythonProcess = spawn('python3',["/home/ubuntu/bot/bot.py", filename]);

    pythonProcess.on('exit', (code) => {
      res.setHeader('Content-type', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document');
      res.setHeader('Transfer-Encoding', 'chunked');
      res.download('/home/ubuntu/bot/output/' + filename.replace('zip', 'docx'));
    });
});

当 child_process 达到“退出”状态时,我收到以下错误。

错误:发送后无法设置标头。

发送请求后几乎立即(约 2 秒)发送响应,即使脚本运行了大约 30 秒。

标签: javascriptnode.jsvue.jsaxioschild-process

解决方案


推荐阅读