nodejs文件实现打包成exe, 并设置开机自启动的方法详解(没有黑窗口)

nodejs打包成exe

使用node的pkg包

# 安装pkg
npm install -g pkg
# 使用pkg打包, 该命令会同时编译 linux, win, mac 版的exe
pkg server.js
# 只打包win版
pkg -t win server.js

如果安装pkg后提示 pkg不是内部命令, 重新打开cmd窗口再试,如果还提示,则需要配置环境变量
查看 .npmrc 文件的配置信息 (默认在C:\Users{用户}下, 如果没有则去 node安装目录下npm下查找)
查看 配置信息中的 prefix 配置路径, 添加到环境变量, 再重启cmd窗口

设置开机自启动 (一)

在打好的exe程序目录下 创建bat文件

# nodejs exe路径
call E:\sdl\server.exe

然后再创建 vbs文件

set ws=WScript.CreateObject("WScript.Shell")
# bat文件路径
ws.Run "E:\sdl\nodeStart.bat",0

在这里插入图片描述

直接运行 server.exe程序会出现黑窗口, 这样运行不会出现黑窗口
然后将vbs文件移动到 C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp 目录下
StarUp目录就是 启动目录
重启计算机即可开机自启动

设置开机自启动 (二)

上面的方式需要用户自己去配置,对于不懂的人不能一键解决问题
下面使用将exe程序打包成windows服务的方式 一键设计开机自启动

首先要下载工具包 winsw
下载winsw程序 链接: https://github.com/winsw/winsw/releases
选择稳定的版本 WinSW v2.11.0 ,直达链接:https://github.com/winsw/winsw/releases/tag/v2.11.0


在这里插入图片描述

软件运行需要.Net Framework软件环境,根据需要下载,一般情况windows是有这个环境的,查看方法 在地址栏上输入C:\Windows\Microsoft.NET\Framework ,按回车键即可查看,缺失下载安装。

然后下载 sample-minimal.xml 配置文件

将这两个文件和 server.exe(node打的exe程序) 放到同一个目录

修改 sample-minimal.xml 配置文件

<service>
 <!-- ID of the service. It should be unique across the Windows system-->
 # 安装windows服务后的服务ID,必须是唯一的。
 <id>nodeStart</id>
 <!-- Display name of the service -->
 # 服务名称,必须是唯一的。一般和id一致即可。
 <name>nodeStart</name>
 <!-- Service description -->
 # 服务描述,可做备注使用。
 <description>nodeStart</description>
 <!-- Path to the executable, which should be started -->
 # 执行的命令
 <executable>%BASE%\server.exe</executable>
 # 日志输出
 <logpath>%BASE%\serviceLogs</logpath>
</service>

然后新建两个 bat文件

install.bat

@echo off
start cmd /k "nodeStart.exe install"
exit

uninstall.bat

@echo off
start cmd /k "nodeStart.exe uninstall"
exit

上述exe程序为 下载的winsw程序包, 我更改了包名

然后运行 install 即可设置开机自启动

PS:这里的bat涉及windows的批处理命令,而对于开机启动项等敏感位置,会有安全软件进行拦截或报警提示,放行即可。

作者:Dylan  Song原文地址:https://blog.csdn.net/weixin_44931584/article/details/128815589

%s 个评论

要回复文章请先登录注册