我正在制作一个节点应用程序,并且已经知道如何在需要时实现代理,但我不确定我实际上如何检查当前系统代理设置。
从我读到它应该在 process.env.http_proxy 中,但在我的 Windows 代理设置中设置代理后未定义。
如何在 NodeJS 中获取当前的代理设置?
您可以使用NPM 中的get-proxy-settings包。
它能够:
从注册表中 Windows 上的 Internet 设置中检索设置
我刚刚在 Windows 10 上测试了它,它能够获取我的代理设置。
或者,您可以查看它们的源代码并自行执行此操作。以下是一些关键功能:
async function getProxyWindows(): Promise<ProxySettings> {
// HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings
const values = await openKey(Hive.HKCU, "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings");
const proxy = values["ProxyServer"];
const enable = values["ProxyEnable"];
const enableValue = Number(enable && enable.value);
if (enableValue > 0 && proxy) {
return parseWindowsProxySetting(proxy.value);
} else {
return null;
}
}
function parseWindowsProxySetting(proxySetting: string): ProxySettings {
if (!proxySetting) { return null; }
if (isValidUrl(proxySetting)) {
const setting = new ProxySetting(proxySetting);
return {
http: setting,
https: setting,
};
}
const settings = proxySetting.split(";").map(x => x.split("=", 2));
const result = {};
for (const [key, value] of settings) {
if (value) {
result[key] = new ProxySetting(value);
}
}
return processResults(result);
}
async function openKey(hive: string, key: string): Promise<RegKeyValues> {
const keyPath = `${hive}\\${key}`;
const { stdout } = await execAsync(`${getRegPath()} query "${keyPath}"`);
const values = parseOutput(stdout);
return values;
}
function getRegPath() {
if (process.platform === "win32" && process.env.windir) {
return path.join(process.env.windir as string, "system32", "reg.exe");
} else {
return "REG";
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
467 次 |
| 最近记录: |