Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node js start and stop windows services

I have a nodeJS app that communicates with a third party application installed as a windows service. My nodeJS application requires this service to be running, however if some circumstances it may not.

Im trying to search for a method to check if this windows service is running and if not start it. After many days searching i have found many results for running a nodeJS application as a windows service but not one providing the ability to start/stop already installed windows services.

Is this even possible? I have found tools like PSEXEC so I could make nodeJS run such a script but it would be preferable if nodeJS could perform this task natively.

Any information to this end would be greatly useful and i find it hard to believe others haven't been in a situation where they have needed to do this also.

Stephen

like image 269
ste2425 Avatar asked May 18 '14 20:05

ste2425


People also ask

How do I start a NodeJS service?

Command to Start forever: To start the forever tool, run the following commands replacing <app_name> with the name of the node. js app. Method 2: The second method involves create a service file and manually starting the app and enabling the service to keep it running in the background.

How do I run a node application as a Windows service?

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.

How do you stop a NodeJS service?

To stop your NodeJS server from running, you can use the ctrl+C shortcut which sends the interrupt signal to the Terminal where you start the server. At other times, you may also want to stop your NodeJS program from running programmatically.

How do I stop node red windows?

You can use Ctrl-C or close the terminal window to stop Node-RED.


1 Answers

In windows, from a command line you can type:

# Start a service
net start <servicename>

# Stop a service
net stop <servicename>

# You can also pause and continue

So, the simple answer is - use child-process to start the service on startup of your server. Something like this:

var child = require('child_process').exec('net start <service>', function (error, stdout, stderr) {
    if (error !== null) {
        console.log('exec error: ' + error);
    }
    // Validate stdout / stderr to see if service is already running
    // perhaps.
});

EDIT: I also found this nodejs module called "windows-service". Seems promising for what you are attempting to do. Some of its functionality is implemented in C++ where it attempts to query the Windows Service Manager.

like image 138
sabhiram Avatar answered Sep 17 '22 13:09

sabhiram