node启动、关闭windows服务

需求:

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'

问题解决:

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值