如何安装node.js作为Windows服务?

我已经下载了node.js可执行文件。 我如何运行该可执行文件作为Windows服务? 我不能使用标准的node.js安装程序,因为我需要同时运行多个版本的node.js。

晚会,但节点窗口也将做的伎俩。

在这里输入图像描述

它也有内置的系统日志。

在这里输入图像描述

有一个API来从代码创build脚本,即

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:我是这个模块的作者。

WinSer是受欢迎的NSSM(Non-Sucking Service Manager)的node.js友好包装器,

作为服务运行

接下来,我想把节点作为一个服务来托pipe,就像IIS一样。 这样,它会启动我的机器,在后台运行,如果崩溃等自动重新启动。

这就是非吸收服务经理nssm进入图片的地方。 这个工具可以让你把一个普通的.exe作为一个Windows服务。

以下是我用来设置节点应用程序实例作为服务的命令,以pipe理员身份打开您的cmd并键入以下命令:

 nssm.exe install service_name c:\your_nodejs_directory\node.exe c:\your_application_directory\server.js net start service_name 

我没有直接解决这个问题,而是提供了一个替代scheme,以更多的node.js时尚的方式来满足你的需求。

function上的要求是:

  1. 让逻辑(app)在后台运行
  2. 能够启动/停止逻辑
  3. 系统启动时自动启动逻辑

这些要求可以通过使用stream程pipe理器(PM)并使stream程pipe理器在系统启动时启动来满足。 两个对Windows友好的PM是:

  • PM2
  • 永远

要使PM自动启动,最简单的方法是使用“At Startup”触发器创build计划任务:

在这里输入图像描述

我发现这个东西非常有用,所以我创build了一个更易于使用的包装(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 –uninstall

 prompt: Service name: [name of your service] prompt: Node script path: [path of your node script] Service stopped Service uninstalled 

一年前我发布的stream程pipe理器+任务调度程序方法在一些一次性服务安装中运行良好。 但最近我开始以微服务的方式devise系统,许多小型服务通过IPC互相通话。 所以手动configuration每个服务已变得无法忍受。

为了实现无需手动configuration安装服务的目标,我创build了serman ,一个命令行工具(使用npm i -g serman安装)将可执行文件安装为服务。 所有你需要写的(只写一次)是一个简单的服务configuration文件以及你的可执行文件。 跑

 serman install <path_to_config_file> 

将安装该服务。 stdoutstderr都被logging下来。 有关更多信息,请查看项目网站 。

工作configuration文件非常简单,如下所示。 但它也有许多有用的function,如下面的<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>