0

I have node js project and ı want the convert windows service and I want it to start automatically.my code turns into windows service, but the requests I make do not come without running the program.

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();

1 Answers1

0

The library itself doesn't provide an explicit option for the config you need. But you can take the help of the command line and the nodeJS itself to do this.

So windows services are manageable from the command line using sc commands

To make changes in startup type you want to use

> sc config <service name> start=<mode>

For reference more details on config command:

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>

So command you want to run is

sc config "Academy Service2" start=auto

That's part 1.

Now part 2, how to run this automatically as part of the code.

After you are done with installing the service and before executing svc.start(); is when you should make this change ideally. We will use child_process provided by NodeJS as an inbuilt capability

The simplest thing to do would be

import { exec } from "child_process";
exec("sc config "Academy Service2" start=auto");

I am pretty sure this will need to happen as admin but can't say for sure.

If you want to ensure its success and log it then some more event listening codes will be needed.

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 });