2017-07-02 78 views
0

我是NodeJS中的新手。我知道我們可以使用pipe()方法將數據傳輸到客戶端。如何管道連接擴展的WriteStream?

下面是代碼

router.get('/archive/*', function (req, res) { 

     var decodedURI = decodeURI(req.url); 
     var dirarr = decodedURI.split('/'); 
     var dirpath = path.join(dir, dirarr.slice(2).join("/")); 
     console.log("dirpath: " + dirpath); 
     var archive = archiver('zip', { 
      zlib: {level: 9} // Sets the compression level. 
     }); 
     archive.directory(dirpath, 'new-subdir'); 
     archive.on('error', function (err) { 
      throw err; 
     }); 
     archive.pipe(res) 
     archive.on('finish', function() { 
      console.log("finished zipping"); 
     }); 
     archive.finalize(); 

    }); 

的片段,當我使用GET請求的壓縮文件下載,但沒有任何擴展。我知道它是因爲我正在寫一個寫入流的響應。無論如何管它擴展名爲.zip?或者我怎樣才能發送壓縮文件,而無需在HDD中創建壓縮文件?

回答

1

的方法之一是管道之前改變接頭,

res.setHeader("Content-Type", "application/zip"); 
res.setHeader('Content-disposition' ,'attachment; filename=downlaod.zip'); 

對於給定代碼,

router.get('/archive/*', function (req, res) { 
     var decodedURI = decodeURI(req.url); 
     var dirarr = decodedURI.split('/'); 
     var dirpath = path.join(dir, dirarr.slice(2).join("/")); 
     var output = fs.createWriteStream(__dirname + '/7.zip'); 
     var archive = archiver('zip', { 
      zlib: {level: 9} // Sets the compression level. 
     }); 
     archive.directory(dirpath, 'new-subdir'); 
     archive.on('error', function (err) { 
      throw err; 
     }); 
     res.setHeader("Content-Type", "application/zip"); 
     res.setHeader('Content-disposition' ,'attachment; filename=downlaod.zip'); 
     archive.pipe(res); 
     archive.finalize(); 

    }); 
1

您可以使用res.attachment()既設置下載的文件名,以及它的MIME類型:

router.get('/archive/*', function (req, res) { 
    res.attachment('archive.zip'); 
    ... 
}); 
+0

但我不想在hdd中創建zip文件。我只是想將歸檔模塊的結果作爲響應 –

+0

請仔細閱讀我鏈接到的文檔:所有'res.attachment'都設置了HTTP標頭。 – robertklep

+0

好的,我明白了。發送附件之前更改其內容類型和內容配置權? –