当前位置:  开发笔记 > 编程语言 > 正文

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

如何解决《节点:res.download下载空的压缩文件夹》经验,为你挑选了1个好方法。

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);

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?



1> 小智..:

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);

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();
  });

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

推荐阅读
郑谊099_448
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有