本文介绍了如何在 Node JS 中获取当前的系统代理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个节点应用程序,并且已经知道如何在需要时实现代理,但我不确定我实际上如何检查当前系统代理设置.

I am making a node application and already know how i can implement a Proxy if required, im not sure how i actually check the current system proxy settings.

从我读到它应该在 process.env.http_proxy 中,但在我的 Windows 代理设置中设置代理后未定义.

From what i read its supposed to be in process.env.http_proxy but thats undefined after setting a proxy in my windows proxy settings.

如何在 NodeJS 中获取当前的 Proxy 设置?

How does one get the current Proxy settings in NodeJS?

推荐答案

您可以使用 来自 NPM 的 get-proxy-settings 包.

它能够:

从注册表中 Windows 的 Internet 设置中检索设置

我刚刚在 Windows 10 上对其进行了测试,它能够获取我的代理设置.

I just tested it on Windows 10 and it was able to get my proxy settings.

或者,您可以查看他们的 并在您的自己的.以下是一些关键功能:

Alternatively, you can take a look at their source and do this on your own. Here are some key functions:

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";
    }
}

这篇关于如何在 Node JS 中获取当前的系统代理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 12:44
查看更多