I have the following express request callback
zip.addLocalFolder(`/path/to/folder`, `./`);
var data = zip.toBuffer();
fs.writeFile(`path/to/download.zip`,data,function (err) {
if (err) return console.log(err);
res.download(`path/to/download.zip`)
});
The fs.writeFile seems to be writing the file after calling the callback function.
Edit: the file is being written successfully. It is the fact that it is being written after I do res.download()
that causes the error
If I call res.download()
in a setTimeout, of 1 second, the execution ends successfully.
I get this error:
ENOENT: no such file or directory, stat 'path/to/download.zip`
Changing the code to
zip.addLocalFolder(`/path/to/folder`, `./`);
var data = zip.toBuffer();
fs.writeFileSync(`path/to/download.zip`,data);
res.download(`path/to/download.zip`);
has the same effect.
The library I use, adm-zip
, has a method for writing the zip file, and working with that has the very same effect.
Is there something I'm missing ?
fs.writeFileAsync(
path/to/download.zip,data);
withfs.writeFileSync(
path/to/download.zip,data);
Check this link for Synchronous file write in nodejs. – LilFlower