Подтвердить что ты не робот

Включение тайм-аута в Node.js http.get при получении большого количества загрузок изображений

Это код, который я использовал для загрузки изображений с URL-адресов:

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);
    });
});

Как я могу добавить тайм-аут для каждого запроса, чтобы он не оставался в ожидании ответа, который является либо большими данными, либо не отвечает?

4b9b3361

Ответ 1

ОК, есть, по крайней мере, два решения вашей проблемы. Легкий:

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

но может быть недостаточно гибким. Более продвинутый:

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 );