dynamic创build多个文件nodejs

我想要下载数据库中的所有文件作为zip文件。

如果我只想下载元素,我可以很容易地设置它的头和内容types,然后可以发送它的缓冲区。

db.collection("resource").find({}).toArray(function(err, result) { res.setHeader('Content-disposition', 'attachment; filename=' + result[0].name); res.contentType(result[0].mimetype); res.send(result[0].data.buffer); } 

现在我想创build一个文件夹,并将每个result元素添加到此文件夹然后发送它。

下面的代码只是返回第一个文件。 这是合理的,因为我立即发送缓冲区。

 for(var i=0; i < result.length; i++){ res.setHeader('Content-disposition', 'attachment; filename=' + result[i].name); res.send(result[i].data.buffer); } 

我想将它们添加到数组中。

 for(var i=0; i < result.length; i++){ var obj = {name: result[i].name, buffer: result[i].data.buffer}; files.push(obj); } res.setHeader('Content-disposition', 'attachment; filename=' + "resource"); res.contentType('application/zip'); res.send(files); 

这返回给我一个文本文件resource ,其中包括作为JSON格式的namebuffer

即使我更新contentType作为应用程序/ zip,它返回为文本格式。

我如何创build这个文件,添加到一个文件夹,并设置文件夹types为zip?

以下片段是适用于我的代码的简化版本。 我不得不删除我的包装,以便更容易理解,所以这可能会导致一些错误的东西。

  function bundleFilesToZip(fileUrls, next) { // step 1) use node's fs library to copy the files u want // to massively download into a new folder //@TODO: HERE create a directory // out of your fileUrls array at location: folderUri // step 2) use the tarfs npm module to create a zip file out of that folder var zipUri = folderUri+'.zip'; var stream = tarfs.pack(folderUri).pipe(fs.createWriteStream(zipUri)); stream.on('finish', function () { next(null, zipUri); }); stream.on('error', function (err) { next(err); }); } // step 3) call the function u created with the files u wish to be downloaded bundleFilesToZip(['file/uri/1', 'file/uri/2'], function(err, zipUri) { res.setHeader('Content-disposition', 'attachment; filename=moustokoulouro'); // step 4) pipe a read stream from that zip to the response with // node's fs library fs.createReadStream(zipUri).pipe(res); }); 

首先,您应该使用官方Express API的res.attachment([filename])http://expressjs.com/en/api.html

您也可以使用adm-zip模块来创buildzip文件夹( https://www.npmjs.com/package/adm-zip