2015-12-02 74 views
0

我的用例是這樣的,我必須創建一個文件目錄並將其作爲用戶的zip文件返回。節點:res.download下載空的壓縮文件夾

我的代碼如下所示:

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在其服務器的位置包含數據。

我意識到這是因爲節點不在等待append()將文件追加到檔案。 我試圖把下載的代碼放在append.finalize()的回調函數中,但它不起作用。

我在哪裏放置下載代碼,以便在append成功後發生?

+0

查看示例https://github.com/archiverjs/node-archiver/blob/master/examples/pack-zip.js – Molda

+0

@Molda該示例不包括下載到客戶端 - 我在哪裏面臨問題。 – Ketcomp

+1

好,但它涵蓋了如何使用output.on創建文件('close' – Molda

回答

2

只需在他們的GitHub存儲庫上查看他們的Example即可。

您可以在res上設置Attachment屬性,然後通過管道連接到它。

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

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

您還必須密切注意有關「關閉」資源的能夠結束流時一切都做。

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

這樣,你仍然可以完成,但一旦一切都做,只會出現下載。

+0

仍然收到一個空文件? –