2015-07-03 30 views
1

運行下面的代碼以下載和解壓縮文件。它的工作原理爲目的,當我嘗試用一​​個,但是當我在同一時間,我得到了下面的錯誤做多:錯誤的標題檢查zlib

Error: incorrect header check at Zlib._handle.onerror

var downloadUnzipFile = function (mID) { 
     try { 
     // Read File  
     console.log("Started download/unzip of merchant: " + mID + " @ " + new Date().format('H:i:s').toString()); 
     request(linkConst(mID)) 
      // Un-Gzip 
      .pipe(zlib.createGunzip()) 
      // Write File 
      .pipe(fs.createWriteStream(fileName(mID))) 
      .on('error', function (err) { 
      console.error(err); 
      }) 
      .on('finish', function() { 
      console.log("CSV created: " + fileName(mID)); 
      console.log("Completed merchant: " + mID + " @ " + new Date().format('H:i:s').toString()); 
      //console.log("Parsing CSV..."); 
      //csvReader(fileName); 
      }); 

     } catch (e) { 
     console.error(e); 
     } 
    } 


    module.exports = function(sMerchants) { 
     var oMerchants = JSON.parse(JSON.stringify(sMerchants)); 
     oMerchants.forEach(function eachMerchant(merchant) { 
     downloadUnzipFile(merchant.merchant_aw_id); 
     }) 
    }; 

任何想法? 感謝

編輯:

爲了澄清,我想通過數組中的每一項(商家)(商家)運行,並下載文件+解壓縮。我目前這樣做的方式意味着它的下載/壓縮發生在同一時間(我認爲這可能導致錯誤)。當我刪除foreach循環,並試圖下載/壓縮一個商家代碼的作品。

+0

「一個」,「多個」 - 你的意思是,一次一個文件與一些文件的順序? – usr2564301

回答

0

是的,正如你所建議的那樣,如果你試圖同時解壓太多文件,你可能會用完內存。因爲您正在處理流,所以解壓縮操作是異步的,這意味着您的每個解壓縮操作完成之前將繼續調用您的循環。有很多節點包允許你處理異步操作,所以你可以依次運行解壓縮函數,但最簡單的方法可能就是使用遞歸函數調用。例如:

var downloadUnzipFile = function (mID) { 
    try { 
    // Read File  
    console.log("Started download/unzip of merchant: " + mID + " @ " + new Date().format('H:i:s').toString()); 
    return request(linkConst(mID)) 
     // Un-Gzip 
     .pipe(zlib.createGunzip()) 
     // Write File 
     .pipe(fs.createWriteStream(fileName(mID))) 
    } catch (e) { 
    console.log(e); 
    return false; 
    } 
} 


module.exports = function(sMerchants) { 
    var merchants = JSON.parse(JSON.stringify(sMerchants)), 
     count = 0; 

    downloadUnzipFile(merchants[count][merchant_aw_id]) 
    .on('error', function(err){ 
     console.log(err); 
     // continue unzipping files, even if you encounter an error. You can also remove these lines if you want the script to exit. 
     if(merchants[++count]){ 
     downloadUnzipFile(merchants[count][merchant_aw_id]); 
     } 
    }) 
    .on('finish', function() { 
     if(merchants[++count]){ 
     downloadUnzipFile(merchants[count][merchant_aw_id]); 
     } 
    }); 
}; 

當然沒有測試過。主要想法應該認真思考:只要前面的調用錯誤退出或結束,只要商家數組中仍有項目,就會遞歸地調用downloadUnzipFile

+0

雖然現在我重讀了你的問題,但是你遇到的錯誤與內存無關,而是試圖解壓縮一個zlib不支持的文件。請參閱http://stackoverflow.com/questions/31438855/error-incorrect-header-check-when-running-post。不過,如果你同時運行你的請求,你仍然可能遇到處理內存的問題。 –