Search code examples
node.jsnode-https

Why isn't timeout doing what I expect it to for https node module?


I have code like this:

const https = require('https');

const request = async (data, options) => {
  return new Promise((resolve, reject) => {
    const req = https.request(options, function(res) {
      const chunks = [];

      res.on('data', function(chunk) {
        chunks.push(Buffer.from(chunk));
      });

      res.on('end', function() {
        let body = Buffer.concat(chunks);

        body = body.toString();

        resolve(body);
      });
    });

    if (data) {
      req.write(JSON.stringify(data));
    }

    // this never fires, tried after comment below
    req.on('timeout', () => {
      console.log("This timed out")
    })

    // handle connection errors
    req.on('error', reject);
    req.end();
  });
};

async function run() {
  try {
    const response = await request(null, {
      method: 'GET',
      hostname: 'example.com',
      timeout: 1,
      path: '/',
      headers: {
        'Content-Type': 'application/json'
      }
    });
    console.log(response);
  } catch (e) {
    console.log(e);
  }
}



run();

The docs at https://nodejs.org/api/http.html#http_http_request_options_callback say this about timeout:

A number specifying the socket timeout in milliseconds. This will set the timeout before the socket is connected.

My call is obviously going to take more than 1MS, yet I am not getting any errors thrown. What am I missing here?

Update

I am able to get req.on('timeout' to work when I am using http module rather than https. Not sure why that would be different? I literally can change require('https') to require('http') and see everything work as expected. The docs say options should be identical, but with different defaults.


Solution

  • Your exact code with require('https') runs properly on Node.js 10, 12 and 13 on macOS Catalina with nvm. I get the following console log:

    This timed out
    {"error_code":"401013","message":"Oauth token is not valid"}
    

    This means that whatever issue you are facing, it is related to your environment or to a bug in a specific (old) Node.js version.

    Try reinstalling Node.js after clearing all your system cache, temporary files and Node.js-related configuration files.