为什么超时没有按照我对 https 节点模块的预期进行?

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

我有这样的代码:

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

https://nodejs.org/api/http.html#http_http_request_options_callback 的文档是这样说的 timeout:

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

我的调用显然会超过 1MS,但我没有收到任何错误。我在这里错过了什么?

更新

当我使用 http 模块而不是 https 时,我能够让 req.on('timeout' 工作。不确定为什么会有所不同?我真的可以将 require('https') 更改为 require('http') 并看到一切都按预期工作。文档说选项应该相同,但默认值不同。

您使用 require('https') 的确切代码可以在带有 nvm 的 macOS Catalina 上的 Node.js 101213 上正常运行。我得到以下控制台日志:

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

这意味着无论您遇到什么问题,它都与您的环境或特定(旧)Node.js 版本中的错误有关。

清除所有系统缓存、临时文件和 Node.js 相关配置文件后,尝试重新安装 Node.js。