Sto cercando di creare un downloader di file come servizio in background ma quando un file di grandi dimensioni è pianificato, viene prima messo in memoria e quindi, al termine del download il il file è scritto sul disco.Scarica file di grandi dimensioni con node.js evitando l'elevato consumo di memoria
Come posso fare in modo che il file venga scritto in modo graduale sul disco preservando la memoria considerando che potrei avere molti file scaricati nello stesso momento?
Ecco il codice `m utilizzando:
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");
});
});
Qualsiasi possibilità che tu possa condividere il risultato finale ? Sto cercando qualcosa di simile a questo ... – Eli
Ho provato a implementare una funzionalità per seguire i reindirizzamenti 302 ma non penso che funzioni correttamente. Forse potresti provare. Eccolo: https://gist.github.com/1297063 – Carlosedp