如何在Node.js中下载文件之前等待文件创建



我有一个使用node和express构建的web应用程序,它使用python脚本生成excel文件。问题是,尽管节点成功地处理了创建excel文件的请求,但处理程序也试图下载刚刚创建的文件,但给出了错误:Error: ENOENT: no such file or directory。我认为这是因为它试图在创建文件之前访问该文件,但我认为使用await会首先创建该文件。这是我的代码:

路线:

router.post('/executepythonscript', db.executePythonScript)

经办人:

const executePythonScript = async (request, response) => {
const { spawn } = require('child_process');
let pythonPromise = new Promise((resolve, reject) => {
const python = spawn('py', ['./scripts/generate_excel.py', request.body.week]);

python.stdout.on("data", (data) => {
resolve(data.toString());
});
python.stderr.on("data", (data) => {
reject(data.toString());
});
python.on('close', (code) => {
console.log(`child process exited with code ${code}`);
});
});
try {
await pythonPromise;
} catch (error) {
console.log(error);
}
response.download('[myPath]/timetracking.xlsx');
}

我使用await是错误的吗?或者为什么程序会在创建文件之前尝试打开它?

去掉函数中的try/catch语句,并将response.download()添加到python.on(close)中。它应该是这样的:

const { spawn } = require('child_process');
const python = spawn('py', ['./scripts/generate_excel.py', request.body.week]);
python.stderr.on("data", (data) => {
console.log(data.toString());
});
python.on('close', (code) => {
console.log(`child process exited with code ${code}`);
response.download('[Path]/tracking/timetracking.xlsx');
});

最新更新