我試圖創建一個文件下載程序作爲後臺服務,但是當計劃一個大文件時,它首先放在內存中,然後在下載結束時文件被寫入磁盤。使用node.js下載大文件以避免高內存消耗
考慮到我可能同時有很多文件正在下載,我該如何讓文件逐漸寫入磁盤保留內存?
這裏使用的代碼我真的:
var sys = require("sys"),
http = require("http"),
url = require("url"),
path = require("path"),
fs = require("fs"),
events = require("events");
var downloadfile = "http://nodejs.org/dist/node-v0.2.6.tar.gz";
var host = url.parse(downloadfile).hostname
var filename = url.parse(downloadfile).pathname.split("/").pop()
var theurl = http.createClient(80, host);
var requestUrl = downloadfile;
sys.puts("Downloading file: " + filename);
sys.puts("Before download request");
var request = theurl.request('GET', requestUrl, {"host": host});
request.end();
var dlprogress = 0;
setInterval(function() {
sys.puts("Download progress: " + dlprogress + " bytes");
}, 1000);
request.addListener('response', function (response) {
response.setEncoding('binary')
sys.puts("File size: " + response.headers['content-length'] + " bytes.")
var body = '';
response.addListener('data', function (chunk) {
dlprogress += chunk.length;
body += chunk;
});
response.addListener("end", function() {
fs.writeFileSync(filename, body, 'binary');
sys.puts("After download finished");
});
});
任何機會,你可以分享的最終結果?我正在尋找這樣的東西... – Eli 2011-10-07 17:40:20
我試圖實現一個功能,遵循302重定向,但我不認爲它的工作正常。也許你可以試試。那裏是:https://gist.github.com/1297063 – Carlosedp 2011-10-18 23:33:34