Home

Awesome

Node Timeouts

An unresponsive service can be worse than a down one. It can tie up your entire system if not handled properly. All network requests should have a timeout.

Here’s how to add timeouts for popular Node packages. All have been tested. The default is no timeout, unless otherwise specified. Enjoy!

Also available for Ruby, Python, Go, and Rust

Build Status

Packages

Standard library

NPM

Standard Library

child_process

exec(cmd, {timeout: 1000});

dns

new dns.Resolver({timeout: 1000});

http

http.request(url, {timeout: 1000});

net

const socket = new net.Socket();
socket.setTimeout(1000);

NPM

axios

axios.get(url, {timeout: 1000});
// or
const instance = axios.create();
instance.defaults.timeout = 1000;

cassandra-driver

const client = new cassandra.Client({
  socketOptions: {
    connectTimeout: 1000,
    readTimeout: 1000
  }
});

got

await got(url, {timeout: 1000});

mongodb

const client = new MongoClient(uri, {
  connectTimeoutMS: 1000,
  socketTimeoutMS: 1000,
  serverSelectionTimeoutMS: 1000
});

mysql

const connection = mysql.createConnection({
  connectTimeout: 1000
});

Default: 10s connect timeout

pg

new Client({connectionTimeoutMillis: 1000});

redis

redis.createClient({connect_timeout: 1000});

@elastic/elasticsearch

new Client({requestTimeout: 1000});

Default: 30s

@opensearch-project/opensearch

new Client({requestTimeout: 1000});

Default: 30s

Don’t see a library you use?

Let us know. Even better, create a pull request for it.

Running the Tests

git clone https://github.com/ankane/node-timeouts.git
cd node-timeouts
npm install

To run all tests, use:

npm test

To run individual tests, use:

npm test test/http.test.js