在node.js中通过node-fetch重用TCP连接

Ofe*_*r B 8 http fetch node.js node-fetch

我正在使用这个函数来调用外部API

const fetch = require('node-fetch');

fetchdata= async function (result = {}) {
  var start_time = new Date().getTime();

    let response = await fetch('{API endpoint}', {
      method: 'post',
      body: JSON.stringify(result),
      headers: { 'Content-Type': 'application/json' },
      keepalive: true

    });

  console.log(response) 
  var time = { 'Respone time': + (new Date().getTime() - start_time) + 'ms' };
  console.log(time)
  return [response.json(), time];
  
}
Run Code Online (Sandbox Code Playgroud)

问题是,我不确定每次使用此函数时,node.js 是否都会重用与 API 的 TCP 连接,尽管我定义了 keepalive 属性。

重用 TCP 连接可以显着提高响应时间
任何建议都将受到欢迎。

Ila*_*mer 23

如https://github.com/node-fetch/node-fetch#custom-agent中所述

const fetch = require('node-fetch');

const http = require('http');
const https = require('https');

const httpAgent = new http.Agent({ keepAlive: true });
const httpsAgent = new https.Agent({ keepAlive: true });
const agent = (_parsedURL) => _parsedURL.protocol == 'http:' ? httpAgent : httpsAgent;

const fetchdata = async function (result = {}) {
    var start_time = new Date().getTime();

    let response = await fetch('{API endpoint}', {
        method: 'post',
        body: JSON.stringify(result),
        headers: { 'Content-Type': 'application/json' },
        agent
    });

    console.log(response)
    var time = { 'Respone time': + (new Date().getTime() - start_time) + 'ms' };
    console.log(time)
    return [response.json(), time];

}
Run Code Online (Sandbox Code Playgroud)