美文网首页
Nodejs 根据端口获取进程信息

Nodejs 根据端口获取进程信息

作者: 木木111314 | 来源:发表于2023-11-21 14:00 被阅读0次

    Nodejs 根据端口获取进程信息
    根据端口结束进程
    根据名称结束进程

    const childProcess = require('child_process'); // nodeJS 自带
    const { execSync } = require('child_process');
    const exec = childProcess.exec;
    const os = require('os');
    const platform = os.platform();
    
    const Log = require('./logUtil')
    
    function viewProcessMessage(name, cb) {
        // process 不用引入,nodeJS 自带
        // 带有命令行的list进程命令是:“cmd.exe /c wmic process list full”
        //  tasklist 是没有带命令行参数的。可以把这两个命令再cmd里面执行一下看一下效果
        // 注意:命令行获取的都带有换行符,获取之后需要更换换行符。可以执行配合这个使用 str.replace(/[\r\n]/g,""); 去除回车换行符 
        let processes = []
        let cmd = process.platform === 'win32' ? 'tasklist' : 'ps aux'
        try {
            exec(cmd, function (err, stdout, stderr) {
                if (err) {
                    return console.error(err)
                }
                // console.log(stdout)
                stdout.split('\n').filter((line) => {
                    let processMessage = line.trim().split(/\s+/)
                    let processName = processMessage[0] //processMessage[0]进程名称 , processMessage[1]进程id
                    if (processName === name) {
                        processes.push(processMessage[1])
                    }
                })
                cb ? cb(processes) : ""
            }, function (e) {
                console.error(e)
            })
        } catch (e) {
            Log.Info(e)
        }
    
    
    }
    
    // viewProcessMessage('name.exe',function (msg) {
    //   //关闭匹配的进程
    //   process.kill(msg)
    // })
    
    const stopByName = function (name) {
        viewProcessMessage(name, (list) => {
            if (list && list.length) {
                for (var i = 0; o < list.length; i++) {
                    let p = list[i];
                    process.kill(p)
                }
            }
        })
    }
    
    
    const GetProcessInfoByPort = (port) =>
        new Promise((resolve, reject) => {
            if (platform === 'win32') {
                const order = `netstat -aon | findstr ${port}`;
                try {
                    const stdout = execSync(order);
                    const portInfo = stdout.toString().trim().split(/\s+/);
                    const pId = portInfo[portInfo.length - 1];
                    const processStdout = execSync(`tasklist | findstr ${pId}`);
                    const [pName] = processStdout.toString().trim().split(/\s+/);
                    resolve({
                        pId,
                        pName,
                    });
                } catch (error) {
                    reject(error);
                }
            } else {
                const order = `lsof -i :${port}`;
                try {
                    const stdout = execSync(order);
                    const [pName, pId] = stdout
                        .toString()
                        .trim()
                        .split(/\n/)[1]
                        .split(/\s+/);
                    resolve({
                        pId,
                        pName,
                    });
                } catch (error) {
                    reject(error);
                }
            }
        });
    
    // 删除占用端口的进程
    const KillByPort = async (port, title) => {
        try {
            let pinfo = await GetProcessInfoByPort(port)
            if (pinfo) {
                console.log(pinfo)
                Log.Info(`停止${title || ""}进程:${pinfo.pName}-${pinfo.pId}`)
                process.kill(pinfo.pId)
            }
        } catch (e) {
            console.log("")
        }
    }
    module.exports = { viewProcessMessage, stopByName, GetProcessInfoByPort, KillByPort }
    
    

    相关文章

      网友评论

          本文标题:Nodejs 根据端口获取进程信息

          本文链接:https://www.haomeiwen.com/subject/ebibwdtx.html