2016-10-25 47 views
0

我們有一個Web應用程序,在訪問該URL時,將準備並生成一個.zip文件,然後下載。HTTP請求,直到標題有附件

我需要使用requestjs創建一個nodejs應用程序,它可以不斷髮出請求,直到有附件標題,從中可以下載它。

生成.zip文件的頁面包含一個簡單的html消息,指出該文件正在準備下載。使用加載時調用的javascript reload(true)函數。

我不確定這是否是正確的做法,但我樂於接受建議。

回答

1

你可以使用async.until遍歷一些邏輯,直到頭可用:

let success = true; 
async.until(
    // Do this as a test for each iteration 
    function() { 
     return success == true; 
    }, 
    // Function to loop through 
    function(callback) { 
     request(..., function(err, response, body) { 
      // Header test 
      if(resonse.headers['Content-Disposition'] == 'attatchment;filename=...') { 
       response.pipe(fs.createWriteStream('./filename.zip')); 
       success = true; 
      } 
      // If you want to set a timeout delay 
      // setTimeout(function() { callback(null) }, 3000); 
      callback(null); 
     }); 
    }, 
    // Success! 
    function(err) { 
     // Do anything after it's done 
    } 
) 

您可以用類似的setInterval一些其他的方式做到這一點,但我會選擇異步使用友好的異步功能。

編輯:這是一個使用setTimeout(我不喜歡用setInterval初始延遲另一個例子

let request = require('request'); 

let check_loop =() => { 
    request('http://url-here.tld', (err, response, body) => { 
     // Edit line below to look for specific header and value 
     if(response.headers['{{HEADER_NAME_HERE}}'] == '{{EXPECTED_HEADER_VAL}}') 
     { 
      response.pipe(fs.createWriteStream('./filename.zip')); // write file to ./filename.zip 
     } 
     else 
     { 
      // Not ready yet, try again in 30s 
      setTimeout(check_loop, 30 * 1000); 
     } 
    }); 
}; 

check_loop(); 
+0

我似乎無法得到你的答案工作,你有使用的例子。 setInterval? – MindVox

+0

我已經用另一個例子更新了我的答案,它很快且很髒,所以你可能需要稍微調整一下。 – Ding

+0

感謝你的回答,令人煩惱的是你的例子不起作用,因爲請求只是重複,而且會話不保持 我不確定是否需要額外的請求sts從第一。或者使用流來檢查標題,以保持連接。 – MindVox