2012-10-09 7 views
10

Questo è il codice che ho utilizzato per scaricare immagini da URL:Compreso timeout in Node.js http.get mentre ottenere gran numero di download di immagini

http.get(options, function (res) { 
    res.on('data', function (data) { 
     file.write(data); 
    }).on('end', function() { 
     file.end(); 
     console.log(file_name + ' downloaded '); 
     cb(null, file.path); 
    }).on('error', function (err) { 
     console.log("Got error: " + err.message); 
     cb(err, null); 
    }); 
}); 

Come posso aggiungere un timeout per ogni richiesta in modo che non rimanga in attesa di una risposta che è di grandi dimensioni o non risponde?

+2

Suona come un buon piano. Che cosa hai provato? – lanzz

+1

Usa questo: http://nodejs.org/api/http.html#http_request_settimeout_timeout_callback – freakish

+0

Ma come dovrei usare con oggetto risposta qui ??? – user1386776

risposta

29

OK, ci sono almeno due soluzioni al tuo problema. Semplice:

var request = http.get(options, function (res) { 
    // other code goes here 
}); 
request.setTimeout(10000, function() { 
    // handle timeout here 
}); 

ma potrebbe non essere abbastanza flessibile. Il più avanzato:

var timeout_wrapper = function(req) { 
    return function() { 
     // do some logging, cleaning, etc. depending on req 
     req.abort(); 
    }; 
}; 

var request = http.get(options, function (res) { 
    res.on('data', function (data) { 
     file.write(data); 
     // reset timeout 
     clearTimeout(timeout); 
     timeout = setTimeout(fn, 10000); 
    }).on('end', function() { 
     // clear timeout 
     clearTimeout(timeout); 
     file.end(); 
     console.log(file_name + ' downloaded '); 
     cb(null, file.path); 
    }).on('error', function (err) { 
     // clear timeout 
     clearTimeout(timeout); 
     console.log("Got error: " + err.message); 
     cb(err, null); 
    }); 
}); 

// generate timeout handler 
var fn = timeout_wrapper(request); 

// set initial timeout 
var timeout = setTimeout(fn, 10000); 
+0

Si è verificato un errore nella versione avanzata del codice: impostazione timeout iniziale 'var timeout = setTimeout (fn, 10000);' deve essere al di fuori della callback 'http.get'. – zavg

+0

@zavg Hai ragione, risolto. – freakish

+6

Quali sono i limiti del primo metodo? – Robotbugs

Problemi correlati