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

Node: res.download downloads empty zipped folder

我的用例是这样的,我必须创建一个文件目录并将其 return 作为用户的 zip 文件。

我的代码如下所示:

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

这让我在浏览器的下载位置出现了一个空文件夹。

然而,其服务器位置的 target.zip 包含数据。

我意识到这是因为 Node 没有等待 append() 将文件附加到存档。 我试过把下载的代码放在append.finalize()的回调函数里,但是不行。

我应该把下载代码放在哪里,以便在附加成功后发生?

看看他们 GitHub 存储库中的 Example

您可以在 res 上设置 Attachment 属性,然后通过管道连接到它。

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

  //this is the streaming magic
  archive.pipe(res);

您还必须在 'close' 上监控 res,以便能够在一切完成后结束流。

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

这样你仍然可以完成,但下载只会在一切都完成后才会发生。