我有node js项目,我想转换windows服务和我想让它自动启动。我的代码变成了windows服务,但是我发出的请求不会在不运行程序的情况下出现。
var Service = require("node-windows").Service;
const svc = new Service({
name: "Academy Service2",
description: "My Node.js application as a Windows service.",
script: "C:\Users\Ata\Desktop\Academy_APP\index.js",
env: {
PORT: 5055,
DB_HOST: "localhost",
DB_PORT: 5432,
DB_DATABASE: "academy",
DB_USER: "postgres",
DB_PASSWORD: "*******",
JWT_SECRET_TOKEN: "abcdndgjdfkdfdkdfgdg",
},
});
svc.on("install", function () {
svc.start();
});
svc.install();
库本身没有为您需要的配置提供显式选项。但是你可以在命令行和nodeJS本身的帮助下完成这个任务。
所以windows服务可以使用sc从命令行管理命令
要更改启动类型,请使用
> sc config <service name> start=<mode>
查看config命令的详细信息:
DESCRIPTION:
Modifies a service entry in the registry and Service Database.
USAGE:
sc <server> config [service name] <option1> <option2>...
OPTIONS:
NOTE: The option name includes the equal sign.
A space is required between the equal sign and the value.
To remove the dependency, use a single / as dependency value.
type= <own|share|interact|kernel|filesys|rec|adapt|userown|usershare>
start= <boot|system|auto|demand|disabled|delayed-auto>
error= <normal|severe|critical|ignore>
binPath= <BinaryPathName to the .exe file>
group= <LoadOrderGroup>
tag= <yes|no>
depend= <Dependencies(separated by / (forward slash))>
obj= <AccountName|ObjectName>
DisplayName= <display name>
password= <password>
所以你要运行的命令是
sc config "Academy Service2" start=auto
这是第一部分。
现在是第2部分,如何将其作为代码的一部分自动运行。
服务安装完成后,执行svc.start();你应该在什么时候做出理想的改变。我们将使用child_process由NodeJS提供的内置功能
最简单的做法是
import { exec } from "child_process";
exec("sc config "Academy Service2" start=auto");
我很确定这将需要发生作为管理员,但不能说肯定。
如果你想确保它的成功并记录它,那么就需要一些更多的事件监听代码。
import { ChildProcess, exec } from "child_process";
let myProcess = exec("sc config "Academy Service2" start=auto");
myProcess.kill();
myProcess.stdout.on("data", data => { YOUR CODE TO HANDLE DATA PRINTED ON CONSOLE });
myProcess.stderr.on("data", errData => { YOUR CODE TO HANDLE ERROR DATA });
myProcess.on("close", (code: number, signal: string) => { YOUR CODE TO HANDLE SHELL CLOSING });