43 lines
1.5 KiB
JavaScript
43 lines
1.5 KiB
JavaScript
// undici-proxy-bootstrap.js
|
|
// 让 Node.js 原生 fetch (undici) 和 ws 包 (WebSocket) 都通过 HTTP 代理连接
|
|
// 用法: NODE_OPTIONS="--require /path/to/undici-proxy-bootstrap.js" npx ...
|
|
|
|
const proxyUrl = process.env.https_proxy || process.env.HTTPS_PROXY || process.env.http_proxy || process.env.HTTP_PROXY;
|
|
|
|
if (proxyUrl) {
|
|
// 1. undici 代理: 覆盖 Node.js 原生 fetch()
|
|
try {
|
|
let undici;
|
|
try {
|
|
undici = require('undici');
|
|
} catch {
|
|
const path = require('path');
|
|
const nvmDir = path.join(process.execPath, '..', '..', 'lib', 'node_modules', 'undici');
|
|
undici = require(nvmDir);
|
|
}
|
|
const agent = new undici.ProxyAgent(proxyUrl);
|
|
undici.setGlobalDispatcher(agent);
|
|
} catch (e) {
|
|
// undici 不可用时静默跳过
|
|
}
|
|
|
|
// 2. global-agent 代理: 覆盖 http.request / https.request (影响 ws 包的 WebSocket 连接)
|
|
try {
|
|
let globalAgent;
|
|
try {
|
|
globalAgent = require('global-agent');
|
|
} catch {
|
|
const path = require('path');
|
|
const gaDir = path.join(process.execPath, '..', '..', 'lib', 'node_modules', 'global-agent');
|
|
globalAgent = require(gaDir);
|
|
}
|
|
// global-agent 通过环境变量读取代理地址
|
|
process.env.GLOBAL_AGENT_HTTP_PROXY = proxyUrl;
|
|
process.env.GLOBAL_AGENT_HTTPS_PROXY = proxyUrl;
|
|
process.env.GLOBAL_AGENT_NO_PROXY = '127.0.0.1,localhost';
|
|
globalAgent.bootstrap();
|
|
} catch (e) {
|
|
// global-agent 不可用时静默跳过
|
|
}
|
|
}
|