Node.js fetch 实用超时与响应体读取
fetch() 的 Promise 在拿到响应头后就可能完成,响应体还在传输。只给等待响应头的代码计时,无法限制后续的 response.text()。下面把一个超时信号同时用于请求和读取,让两段共用同一份时间预算。
一个可复制的实现
保存为 fetch-text.mjs。示例只处理 GET,默认跟随重定向并检查最终响应;成功时返回完整文本,非 2xx 响应会丢弃响应体并抛出 HTTP 状态错误。
export async function fetchText(url, timeoutMs = 2000) {
if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 2147483647) {
throw new RangeError('timeoutMs must be an integer from 1 to 2147483647');
}
const signal = AbortSignal.timeout(timeoutMs);
let phase = 'headers';
try {
const response = await fetch(url, { signal });
if (!response.ok) {
const httpError = new Error(`HTTP ${response.status}`);
httpError.name = 'HttpStatusError';
httpError.status = response.status;
if (response.body) await response.body.cancel().catch(() => {});
throw httpError;
}
phase = 'body';
return await response.text();
} catch (error) {
if (error === signal.reason) {
const timeout = new Error(`Request exceeded ${timeoutMs} ms`, { cause: error });
timeout.name = 'RequestTimeoutError';
timeout.phase = phase;
throw timeout;
}
if (error.name === 'HttpStatusError') throw error;
const failure = new Error(`Fetch failed during ${phase}`, { cause: error });
failure.name = 'FetchError';
failure.phase = phase;
throw failure;
}
}
对已提供的 URL,可在另一个 .mjs 文件中这样调用(实际运行前将地址替换为自己的服务):
import { fetchText } from './fetch-text.mjs';
const url = 'http://127.0.0.1:3000/';
try {
const text = await fetchText(url, 2000);
console.log(text);
} catch (error) {
if (error.name === 'RequestTimeoutError') {
console.error('请求超时,阶段:', error.phase);
} else if (error.name === 'HttpStatusError') {
console.error('HTTP 状态:', error.status);
} else {
console.error('请求或读取失败:', error.cause ?? error);
}
}
phase 为 headers 时,表示尚未取得最终响应对象,其中也包含建立连接等步骤;body 表示已经取得响应,正在读取正文。return await 不能在这里省略:它让读取时的拒绝也进入当前的 catch。
fetch 收到 404 或 500 时通常不会因为状态码而拒绝,因此必须检查 response.ok。示例对非 2xx 状态取消未读取的正文;取消失败不会盖过已取得的 HTTP 状态,提前取消也可能使底层连接无法复用。其他请求或读取异常会包装为 FetchError,原始错误保留在 cause。这类错误可能来自网络中断,也可能来自不合法 URL 等问题,不能都当作网络故障。
超时判断使用 error === signal.reason,而不是只看 signal.aborted:否则一个恰好与超时接近的其他错误可能被误判为超时。上述判定和响应体阶段的错误行为已在下述 Node.js 版本测试;换运行时或另行组合取消信号时,应重新验证错误传播。
本地验证
Node.js v22.22.0、Windows,本次测试只在 127.0.0.1 上启动临时 HTTP 服务,由系统分配空闲端口;没有访问外部服务。把以下测试保存为 fetch-text.test.mjs,与上面的模块放在同一目录:
import { test, before, after } from 'node:test';
import assert from 'node:assert/strict';
import { createServer } from 'node:http';
import { fetchText } from './fetch-text.mjs';
let server;
let base;
before(async () => {
server = createServer((req, res) => {
if (req.url === '/ok') {
res.writeHead(200, { 'content-type': 'text/plain; charset=utf-8' });
res.end('hello');
return;
}
if (req.url === '/empty') {
res.writeHead(204).end();
return;
}
if (req.url === '/slow-headers') {
const timer = setTimeout(() => res.end('late'), 3500);
res.once('close', () => clearTimeout(timer));
return;
}
if (req.url === '/redirect') {
res.writeHead(302, { location: '/ok' }).end();
return;
}
if (req.url === '/shared-budget') {
let timer = setTimeout(() => {
res.writeHead(200, { 'content-type': 'text/plain; charset=utf-8' });
res.write('first');
timer = setTimeout(() => res.end('last'), 1000);
}, 900);
res.once('close', () => clearTimeout(timer));
return;
}
if (req.url === '/slow-body') {
res.writeHead(200, { 'content-type': 'text/plain; charset=utf-8' });
res.write('first');
const timer = setTimeout(() => res.end('last'), 3500);
res.once('close', () => clearTimeout(timer));
return;
}
if (req.url === '/slow-404') {
res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' });
res.write('first');
const timer = setTimeout(() => res.end('last'), 3500);
res.once('close', () => clearTimeout(timer));
return;
}
if (req.url === '/drop-connection') {
req.socket.destroy();
return;
}
if (req.url === '/drop-body') {
res.writeHead(200, { 'content-type': 'text/plain; charset=utf-8' });
res.write('first');
const timer = setTimeout(() => res.destroy(), 200);
res.once('close', () => clearTimeout(timer));
return;
}
res.writeHead(404).end();
});
await new Promise((resolve, reject) => {
server.once('error', reject);
server.listen(0, '127.0.0.1', resolve);
});
base = `http://127.0.0.1:${server.address().port}`;
});
after(async () => {
server.closeAllConnections();
await new Promise((resolve, reject) => server.close(err => err ? reject(err) : resolve()));
});
test('rejects invalid timeout values without starting a request', async () => {
for (const value of [-1, 0, 1.5, 4294967296]) {
await assert.rejects(fetchText(`${base}/ok`, value), error => {
assert.equal(error.name, 'RangeError');
return true;
});
}
});
test('reads a successful response body', async () => {
assert.equal(await fetchText(`${base}/ok`, 2000), 'hello');
});
test('follows a redirect by default and reads the final response body', async () => {
assert.equal(await fetchText(`${base}/redirect`, 2000), 'hello');
});
test('reads an empty successful response body', async () => {
assert.equal(await fetchText(`${base}/empty`, 2000), '');
});
test('reports an HTTP error without attempting to read the response body', async () => {
await assert.rejects(fetchText(`${base}/missing`, 2000), error => {
assert.equal(error.name, 'HttpStatusError');
assert.equal(error.status, 404);
return true;
});
});
test('does not wait for a slow HTTP error body', async () => {
await assert.rejects(fetchText(`${base}/slow-404`, 800), error => {
assert.equal(error.name, 'HttpStatusError');
assert.equal(error.status, 404);
return true;
});
});
test('reports a network failure separately from HTTP and timeout errors', async () => {
await assert.rejects(fetchText(`${base}/drop-connection`, 2000), error => {
assert.equal(error.name, 'FetchError');
assert.equal(error.phase, 'headers');
assert.ok(error.cause);
return true;
});
});
test('reports a network interruption during response-body reading', async () => {
await assert.rejects(fetchText(`${base}/drop-body`, 2000), error => {
assert.equal(error.name, 'FetchError');
assert.equal(error.phase, 'body');
assert.ok(error.cause);
return true;
});
});
test('reports a timeout while waiting for response headers', async () => {
await assert.rejects(fetchText(`${base}/slow-headers`, 800), error => {
assert.equal(error.name, 'RequestTimeoutError');
assert.equal(error.phase, 'headers');
assert.equal(error.cause.name, 'TimeoutError');
return true;
});
});
test('applies one shared deadline across headers and body', async () => {
await assert.rejects(fetchText(`${base}/shared-budget`, 1500), error => {
assert.equal(error.name, 'RequestTimeoutError');
assert.equal(error.phase, 'body');
return true;
});
});
test('reports a timeout while reading an unfinished response body', async () => {
await assert.rejects(fetchText(`${base}/slow-body`, 800), error => {
assert.equal(error.name, 'RequestTimeoutError');
assert.equal(error.phase, 'body');
assert.equal(error.cause.name, 'TimeoutError');
return true;
});
});
在已安装 Node.js 22 的环境中运行:
node --version
node --test --test-reporter=spec fetch-text.test.mjs
本次实际运行结果如下,耗时会随机器变化:
v22.22.0
✔ rejects invalid timeout values without starting a request (14.4755ms)
✔ reads a successful response body (48.2676ms)
✔ follows a redirect by default and reads the final response body (10.9329ms)
✔ reads an empty successful response body (5.992ms)
✔ reports an HTTP error without attempting to read the response body (8.7224ms)
✔ does not wait for a slow HTTP error body (9.3023ms)
✔ reports a network failure separately from HTTP and timeout errors (11.9014ms)
✔ reports a network interruption during response-body reading (217.9778ms)
✔ reports a timeout while waiting for response headers (807.6174ms)
✔ applies one shared deadline across headers and body (1512.9308ms)
✔ reports a timeout while reading an unfinished response body (806.9637ms)
ℹ tests 11
ℹ suites 0
ℹ pass 11
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 3743.8882
共享预算测试让服务端约 900 ms 后发送响应头和首段正文,再过 1000 ms 结束正文;客户端总限时 1500 ms。测试断言超时发生在 body 阶段,证明等待响应头所花的时间没有被重新计一遍。
适用范围
AbortSignal.timeout() 在创建时开始计时,包含等待连接、响应头和成功响应正文的时间;这不是分别给每一阶段计时,也不是无数据活动超时。计时依赖事件循环,不能保证精确在截止时刻执行,更不能中断阻塞事件循环的同步代码。
text() 会把整个成功响应体读入内存,适合大小可信的文本;大文件或不可信响应应改为流式读取,并设置字节上限及相应取消逻辑。示例不保留错误响应正文,也没有实现重试、外部主动取消或多个请求共享总预算。timeoutMs 在此实现中必须是 1 到 2147483647 的整数毫秒。
参考资料:Node.js 官方文档《Global objects》中的 AbortSignal.timeout;MDN 文档《Using Fetch》。
本文由AI辅助整理。
- 点赞
- 收藏
- 关注作者
评论(0)