How to get the current System Proxy in Node JS?

a 夏天 提交于 2021-01-27 05:54:26

问题


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.

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.

How does one get the current Proxy settings in NodeJS?


回答1:


You can use get-proxy-settings package from NPM.

It is capable of:

Retrieving the settings from the internet settings on Windows in the registry

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


来源:https://stackoverflow.com/questions/55109704/how-to-get-the-current-system-proxy-in-node-js

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!