javascript - 如何在 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 秒。
解决方案
推荐阅读
- html - 单击按钮时如何显示隐藏图标并删除文本
- python - 基于df中的另一列使用python从teradata数据库中选择行
- r - 如何将使用 geom_label() 制作的标签的文本居中,其垂直位置已被 vjust 更改?(ggplot2 包)
- html - 如何防止 Swiper.js 放大 html 页面?
- spring-security - 使用 Spring Authorization Server 联合授权请求
- node.js - 如何使用节点获取
- oracle - Oracle Spatial 问题:可以使用来自另一个 Oracle 表的查询结果填充 SDO_ORDINATE_ARRAY 吗?
- sql-server - 将表从 SQL Server 传输到 Azure SQL 的最佳方式?
- scala - SBT 1.3.1 中的 OutOfMemoryError 元空间
- javascript - 如何在随机播放数组之前分配重要属性