节点:res.download下载空的压缩文件夹

Ket*_*omp 1 javascript synchronization asynchronous archive node.js

My use case is such where I have to create a directory of files and return it as a zip file for the user.

My code looks like this:

var output = fs.createWriteStream('target.zip');

archive.pipe(output);
archive.append('details.json', { name: 'details.json'});
archive.finalize();

//Specifiy the .zip folder & Download
filename = 'target.zip';
res.download(filename);
Run Code Online (Sandbox Code Playgroud)

This gives me an empty folder in my browser's download location.

The target.zip in its server's location however, contains data.

I realize this is happening because Node is not waiting for append() to append files to the archive. I tried to put the code for download in the callback function of append.finalize() but it doesn't work.

Where do I put the download code so that it happens after the append is successful?

wjv*_*der 5

Just have a look at their Example on their GitHub repository.

You can set the Attachment property on res and then pipe to it.

//set the archive name
  res.attachment('archive-name.zip');

  //this is the streaming magic
  archive.pipe(res);
Run Code Online (Sandbox Code Playgroud)

You must also monitor res's on 'close' to be able to end the stream when everything is done.

res.on('close', function() {
    console.log('Archive wrote %d bytes', archive.pointer());
    return res.status(200).send('OK').end();
  });
Run Code Online (Sandbox Code Playgroud)

That way you can still finalize, but the download will only occur once everything is done.