node启动、关闭windows服务

发布于 2023-03-15 | 作者: 静尾 | 来源: CSDN博客 | 转载于: CSDN博客

需求:

electron 软件启动与关闭要同时开启与关闭一个本地数据转发服务

解决:

工具包:handleWindowsService.ts

	const exec = require('child_process').exec;

const windowServiceStart = function (path: string) { // path必须为绝对路径
    exec(`start ${path}`, function (err: any, stdout: any, stderr: any) {
        if (err) {
            throw err;
        }
    })
}

const windowsServiceStop = function (port: any) { // 服务进程的端口号
    let netstat_command = 'netstat -aon | findstr \":' + port + '\"';
    console.log('查询服务进程...' + netstat_command);
    exec(netstat_command, { maxBuffer: 5000 * 1024 }, (err: any, stdout: any, stderr: any) => {
        if (err) {
            console.log('查询服务进程异常:' + err);
            return false;
        }
        let line = stdout.split('\n')[0]; //第一行信息
        console.log('查询成功,进程信息:' + line);

        let p = line.trim().split(/\s+/);
        let address = p[1];
        let pid = p[4];
        if (address.split(':')[1] != port || !pid || pid.length == 0) {
            console.log('获取进程id失败');
            return false;
        }

        let taskkill_command = 'taskkill /F /pid ' + pid;
        console.log('关闭服务...' + taskkill_command);
        exec(taskkill_command, { maxBuffer: 5000 * 1024 }, function (err: any, stdout: any, stderr: any) {
            if (err) {
                console.log('关闭服务异常:' + err);
                return false;
            }
            console.log('服务关闭成功');
            return true;
        });
    });
};

export {
    windowServiceStart,
    windowsServiceStop
}

配置项:connect.config.ts

	const dataServerUrl = "C:\\Users\\86155\\Desktop\\test\\DataPublish\\DataServer.exe";
const dataServerPort = 7771;

export { wsConnectUrl, connectUrl, dataServerUrl, dataServerPort };

主进程使用:main.ts

	import { windowServiceStart, windowsServiceStop } from './modules/toolsFn/handleWindowsService'
import { dataServerUrl, dataServerPort } from "./modules/config/connect.config";

// 启动数据转发服务
window.onload = function () {
  windowServiceStart(dataServerUrl);
};

// 关闭数据转发服务
window.onbeforeunload = function () {
  windowsServiceStop(dataServerPort);
};

效果预览:

本地服务名为:DataServer
打开软件前的任务管理器:

打开软件后的任务管理器:

关闭软件后的任务管理器:

测试:

可以使用打开windows计算器的方式进行功能测试。
windows计算器的绝对路径:
C:\\Windows\\System32\\calc.exe'