I'm trying to create an archive that contains some .txt files, and then I want to download this archive. See the code below:
async function archiveAndDownload(res) {
const bashCommand = ...
const archive = ...
exec(bashCommand, (err, stdout, stderr) => {
if (err && err.code != 1) {
console.log(err);
res.status(500).json({ error: `Error.` });
return;
} else {
if (stderr) {
console.log(stderr);
}
}
});
res.status(200).download(archive, async (err) => {
if (err) {
console.log("Cannot download the archive " + err);
} else {
fs.unlink(archive);
}
});
}
async function getX(req, res) {
try {
await archiveAndDownload(res);
} catch (err) {
console.log("Error: " + err);
}
}
When trying to test it from Postman, I get this error:
Cannot download the archive Error: Request aborted
How can I solve it? Thank you for your time!
(As a side note, if I try to move the download operation inside exec on else
, it will work, but I wanted to have 2 separate blocks of code)
I figured it out..
The problem was with getX
function. Sadly I forgot that there was a finally
block at the end which always executes..
So the whole getX
function was:
async function getX(req, res) {
try {
await archiveAndDownload(res);
} catch (err) {
console.log("Error: " + err);
} finally {
res.end(); // <<<< this was my problem, I removed the whole finally block
}
}
I'm sorry I didn't write the whole function in this post, but it's good I FINALLY figured it out. Hope this will help someone. So be careful: never res.render
, res.send
, res.end
etc after a res.download
. You need to let the download finish first.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.