2012-07-21 57 views
2

嘿,我是一個真正的初學者,js節點很適合我。我試圖下載一個文件(圖)這是我的代碼:下載具有節點請求的圖像

function downloadFileFromURL(url, callback) 
{ 
    file_name = path.basename(url); 

    var wstream = fs.createWriteStream(file_name); 

    wstream.on('error', function (err) { 
     console.log(err, url); 
    }); 

    wstream.on('close', function(){ 

     console.log("finished downloading: ", url, this.path); 

    }); 

    request(img_url).pipe(wstream); 
} 

如果我解析博客飼料與我的應用程序,這個功能對圖像的一半下載。我可以在瀏覽器中看到圖片。文件被創建,但其中一些留在0字節。

的例子進我解析是:http://feeds.feedburner.com/ButDoesItFloat?format=xml

我看到這裏這個問題:Writing image to local server這是類似的,希望能看到如何與節點要求完成

+0

你到底在問什麼? – Pickels 2012-07-21 14:35:52

+0

對不起,如果這不明確,我的問題是爲什麼有些文件得到完全下載,爲什麼有些不在節點請求模塊,如果有人有類似的問題。在此期間,我對代碼做了更多的工作,並用代碼替換了它:http://stackoverflow.com/questions/5294470/node-js-writing-image-to-local-server現在它工作正常,根本不使用請求模塊。 也許這是一個錯誤,我應該問github上... – 2012-07-21 15:42:17

回答

0

http-get看看到達到它。你只需要傳遞兩個參數,首先是URL,第二個參數是保存文件的路徑,非常簡單。回調函數返回文件名爲「result.file」。查看下面的代碼並試一試:

var http = require('http-get'); 
http.get('www.ohmydear.com/thesite.png', '/path/to/thesite.png', function (error, result) { 
    if (error) { 
     console.error(error); 
    } else { 
     console.log('File downloaded at: ' + result.file); 
    } 
});