Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Including timeout in Node.js http.get while getting large number of image downloads

Tags:

http

node.js

This is the code which I have been using to download images from URLs:

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

How can I add a timeout for every request so that it doesn't stay on waiting for a response which is either large data or unresponsive?

like image 251
user1386776 Avatar asked Oct 09 '12 12:10

user1386776


People also ask

How many concurrent HTTP requests can node js handle?

JS can handle 10,000 concurrent requests they are essentially non-blocking requests i.e. these requests are majorly pertaining to database query.

CAN node js handle high traffic?

Node. js is a powerful JavaScript-based runtime environment that provides the server-side for web applications. It was designed with scalability and performance in mind, making node an ideal solution for high-traffic websites or any other type of application where speed is desired.

What is the default timeout for Node JS?

In Node. js, default server timeout is 0 milliseconds for the latest version and 2min i.e. (120000 milliseconds) for the older version.


Video Answer


1 Answers

OK, there are at least two solutions to your problem. An easy one:

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

but might not be flexible enough. The more advanced one:

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 );
like image 64
freakish Avatar answered Sep 22 '22 05:09

freakish