【问题标题】:How to get the current System Proxy in Node JS?如何在 Node JS 中获取当前的系统代理?
【发布时间】:2019-03-11 20:15:24
【问题描述】:

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

从我读到的内容来看,它应该在 process.env.http_proxy 中,但在我的 Windows 代理设置中设置代理后,那是未定义的。

如何获取 NodeJS 中的当前代理设置?

【问题讨论】:

    标签: node.js proxy


    【解决方案1】:

    你可以使用来自 NPM 的 get-proxy-settings 包。

    它能够:

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

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

    或者,您可以查看他们的source 并自行执行此操作。以下是一些关键功能:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-15
      • 2013-08-23
      • 1970-01-01
      • 1970-01-01
      • 2011-07-02
      • 2016-07-30
      • 2016-02-01
      • 2014-04-21
      相关资源
      最近更新 更多