我已经下载了 node.js 可执行文件。如何将该可执行文件作为 Windows 服务运行? 我无法使用标准的 Node.js 安装程序,因为我需要同时运行多个版本的 Node.js。
聚会迟到了,但是 node-windows 也能解决问题。
它还内置了系统日志记录。
有一个 API 可以从代码创建脚本,即
var Service = require('node-windows').Service;
// Create a new service object
var svc = new Service({
name:'Hello World',
description: 'The nodejs.org example web server.',
script: 'C:\\path\\to\\helloworld.js'
});
// Listen for the "install" event, which indicates the
// process is available as a service.
svc.on('install',function(){
svc.start();
});
svc.install();
FD:我是这个模块的作者。
我发现这个东西非常有用,所以我围绕它构建了一个更容易使用的包装器(npm,github)。
安装:
npm install -g qckwinsvc
安装您的服务:
qckwinsvc
prompt: Service name: [name for your service]
prompt: Service description: [description for it]
prompt: Node script path: [path of your node script]
Service installed
卸载您的服务:
qckwinsvc --卸载
prompt: Service name: [name of your service]
prompt: Node script path: [path of your node script]
Service stopped
Service uninstalled
WinSer 是一个对流行的 NSSM(非吸吮服务管理器)
的 Node.js 友好包装器下一步,我想将节点托管为服务,就像 IIS 一样。这边走 它会与我的机器一起启动,在后台运行,然后重新启动 如果崩溃等情况会自动进行。
这就是非吸服务管理器nssm进入的地方 图片。该工具可让您将普通的 .exe 作为 Windows 服务托管。
这是我用来设置节点实例的命令 应用程序作为服务,像管理员一样打开你的cmd并输入 以下命令:
nssm.exe install service_name c:\your_nodejs_directory\node.exe c:\your_application_directory\server.js net start service_name
我一年前发布的流程管理器+任务调度程序方法对于一些一次性服务安装效果很好。但最近我开始以微服务方式设计系统,许多小服务通过 IPC 相互通信。所以手动配置每个服务已经变得难以忍受。
为了实现无需手动配置即可安装服务的目标,我创建了 serman,一个命令行工具(使用
npm i -g serman
安装)来将可执行文件安装为服务。您需要编写(并且只需编写一次)的只是一个简单的服务配置文件以及可执行文件。运行
serman install <path_to_config_file>
将安装该服务。
stdout
和 stderr
均已记录。欲了解更多信息,请查看项目网站。
工作配置文件非常简单,如下所示。但它也有许多有用的功能,例如下面的
<env>
和<persistent_env>
。
<service>
<id>hello</id>
<name>hello</name>
<description>This service runs the hello application</description>
<executable>node.exe</executable>
<!--
{{dir}} will be expanded to the containing directory of your
config file, which is normally where your executable locates
-->
<arguments>"{{dir}}\hello.js"</arguments>
<logmode>rotate</logmode>
<!-- OPTIONAL FEATURE:
NODE_ENV=production will be an environment variable
available to your application, but not visible outside
of your application
-->
<env name="NODE_ENV" value="production"/>
<!-- OPTIONAL FEATURE:
FOO_SERVICE_PORT=8989 will be persisted as an environment
variable machine-wide.
-->
<persistent_env name="FOO_SERVICE_PORT" value="8989" />
</service>
https://nssm.cc/ 服务助手非常适合通过批处理文件创建 Windows 服务 我使用 nssm 且适用于任何应用程序和任何文件
实际上,node.exe官方不支持Windows Service,exe必须实现3个功能(C/C++):
Service Entry Point
ServiceMain Function
Control Handler
所以,直接注册节点是行不通的(启动服务需要无限的时间)。要解决该问题,请使用 os-service 或 pm2 等第三方库。