2014-07-03 68 views
0

我試圖使用Node.js和Request模塊從Google Drive下載文件。 我從項目元數據的webContentLink區域獲取下載鏈接,這些鏈接在我的瀏覽器中工作。Node.js - 通過請求從Google Drive下載文件

我的要求是這樣的:

request.get({uri:item.webContentLink,headers:{authorization:'Bearer'+token}}).pipe(response); 

我的回答是:

stream.js:79 
dest.end(); 
    ^
TypeError: Object #<IncomingMessage> has no method 'end' 
    at Request.onend (stream.js:79:10) 
    at Request.EventEmitter.emit (events.js:117:20) 

我使用我發現這裏https://github.com/google/google-api-nodejs-client/issues/150

任何幫助將不勝感激方法。

**編輯全碼

var request = require('request'); 

//getting children of folder 
var url = "https://www.googleapis.com/drive/v2/files/"+id+"/children?maxResults=1000&q=trashed%3Dfalse&access_token="+token;; 

request.get(url, function(err,response,body){ 

    detailsParse = JSON.parse(body); 
    //if children are .mp3 then download 

    if(detailsParse.mimeType == 'audio/mpeg'){ 
    var file = fs.createWriteStream("./"+detailsParse.title); 

        var getDown = "https://www.googleapis.com/drive/v2/files/"+detailsParse.id+"?access_token="+token; 
        request.get(getDown, function(err,response,body){ 
         if(err){console.log(err)} 

         var downParse = JSON.parse(body); 
         request.get({uri:downParse.webContentLink,headers:{authorization:'Bearer'+token}}).pipe(response); 
    } 


}) 
+0

什麼是您響應的「響應」? – levi

+0

我正試圖將我收到的請求傳遞給文件。 http://runnable.com/UmhMG6nlm5cPAAAd/download-a-file-with-request-for-node-js-and-webserver 這是我認爲這是可能的另一個鏈接。 – MonsterWimp757

+0

你可以發佈你正在使用的完整代碼嗎? – levi

回答

0

您傳遞給pipe您創建的文件,而不是請求響應。

更改代碼.pipe(response);.pipe(file);

+1

謝謝,但是當我這樣做時,我得到一個空白的mp3文件。標題是正確的,但文件是空的。 – MonsterWimp757

+0

只需使用'request(url).pipe'而不是'request.get(url).pipe' – fmodos

4

好吧,這是錯誤的一對夫婦的部分。 第一@fmodos在將結果傳遞給'我'之前創建的文件'是正確的。

但是這並不完全因爲我遇到了身份驗證問題,而不是用正確的端點問題,解決問題,因此完整的答案是低於

var request = require('request'); 

//getting children of folder 
var url = "https://www.googleapis.com/drive/v2/files/"+id+"/children?maxResults=1000&q=trashed%3Dfalse&access_token="+token; 

request.get(url, function(err,response,body){ 

    detailsParse = JSON.parse(body); 
    //if children are .mp3 then download 

    if(detailsParse.mimeType == 'audio/mpeg'){ 
    var file = fs.createWriteStream("./"+detailsParse.title); 

    var getDown = "https://www.googleapis.com/drive/v2/files/"+detailsParse.id+"?access_token="+token; 
    request.get(getDown, function(err,response,body){ 
     if(err){console.log(err)} 

     var downParse = JSON.parse(body); 
     //****THIS NEEDS TO BE THE downloadUrl ENDPOINT AND NOT THE webContentLink endpoint 

     //*****NOTICE THE SPACE AFTER Bearer WAS MISSING BEFORE 
     request.get({uri:downParse.downloadUrl,headers:{authorization:'Bearer '+token}}).pipe(response); 
    }); 
    } 


}); 
+0

感謝您分享您的代碼!我在一個相似的情況下,你的問題和代碼幫助我進一步,謝謝! – Malin