Javascript 节点:res.download下载空的压缩文件夹
在我的用例中,我必须创建一个文件目录,并将其作为zip文件返回给用户 我的代码如下所示:Javascript 节点:res.download下载空的压缩文件夹,javascript,node.js,asynchronous,synchronization,archive,Javascript,Node.js,Asynchronous,Synchronization,Archive,在我的用例中,我必须创建一个文件目录,并将其作为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 = 't
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存储库中的代码就可以了
您可以在res
上设置Attachment
属性,然后通过管道连接到它
//set the archive name
res.attachment('archive-name.zip');
//this is the streaming magic
archive.pipe(res);
您还必须监视“关闭”上的res,以便在完成所有操作后能够结束流
res.on('close', function() {
console.log('Archive wrote %d bytes', archive.pointer());
return res.status(200).send('OK').end();
});
这样您仍然可以完成,但下载只会在完成所有操作后进行。只需查看他们在GitHub存储库中的内容
res.on('close', function() {
console.log('Archive wrote %d bytes', archive.pointer());
return res.status(200).send('OK').end();
});
您可以在res
上设置Attachment
属性,然后通过管道连接到它
//set the archive name
res.attachment('archive-name.zip');
//this is the streaming magic
archive.pipe(res);
您还必须监视“关闭”上的res,以便在完成所有操作后能够结束流
res.on('close', function() {
console.log('Archive wrote %d bytes', archive.pointer());
return res.status(200).send('OK').end();
});
通过这种方式,您仍然可以完成,但下载只会在完成所有操作后进行。Check example@Molda该示例不包括下载到客户端-我正面临这个问题。好的,但它包括如何查看使用output.on('close')创建文件的时间。那么res.download()可以放在output.on中吗(..的回调函数?我自己还没有试过,但我想说yesCheck example@Molda这个例子不包括下载到客户端-我遇到了这个问题。好的,但它包括了如何查看文件是何时使用output.on('close')创建的,那么res.download()可以放在output.on中吗(..的回调函数?我自己还没试过,但我会说是直到得到一个空文件?还是得到一个空文件?
res.on('close', function() {
console.log('Archive wrote %d bytes', archive.pointer());
return res.status(200).send('OK').end();
});