Use nodejs to open HTTPS 443 port service

Use nodejs to open HTTPS 443 port service

The tool class code is as follows:
proxyUtils

const https = require('https');
const httpProxy = require('http-proxy');
const fs = require("fs");
const Path = require("path");
const {
    
    execSync} = require('child_process');
const process = require("process");

const proxy = httpProxy.createProxyServer();

// 证书配置,通过 KeyManager 生成开发证书。
const options = {
    
    
    key: fs.readFileSync(Path.join(process.cwd(), './data/crt/127.0.0.1_key.key')),
    cert: fs.readFileSync(Path.join(process.cwd(), './data/crt/127.0.0.1_chain.crt')),
};

/**
 * 创建https服务器
 * @returns {Promise<unknown>}
 */
function createHttpsServer() {
    
    
    return new Promise((resolve, reject) => {
    
    
        try {
    
    
            // 用于杀死占用443端口的进程的命令
            const killCmd = 'FOR /F "tokens=5" %P IN (\'netstat -a -n -o ^| findstr :443 ^| findstr /I LISTENING\') DO TaskKill.exe /PID %P /F';
            // 执行命令并等待其完成
            try {
    
    
                execSync(killCmd);
            } catch (err) {
    
    
            }
            https.createServer(options, (req, res) => {
    
    
                if (req.url && (req.url + '').includes('/myCheck')) {
    
    
                    // 直接返回文本
                    res.writeHead(200, {
    
    'Content-Type': 'application/json'});
                    res.end(JSON.stringify({
    
    
                        "消息": "看到我就说明配置成功了!",
                    }, null, 4));
                } else if (req.url && (req.url + '').includes('/myError')) {
    
    
                    // 直接返回文本
                    res.writeHead(200, {
    
    'Content-Type': 'application/json'});
                    res.end(JSON.stringify({
    
    
                        "消息": "配置失败!",
                    }, null, 4));
                } else {
    
    
                    proxy.web(req, res, {
    
    target: 'http://0.0.0.0:8083/'});
                }
            }).listen(443);
            console.log('https服务器启动成功!');
            resolve();
        } catch (e) {
    
    
            console.log('https服务器启动失败!');
            reject(e);
        }
    });
}


module.exports = {
    
    
    createHttpsServer
}

// 测试代码
createHttpsServer();

Guess you like

Origin blog.csdn.net/WSYLH/article/details/131440742