How to use NSSM to run Node JS as a service in Windows

Run Node.JS as a Service
in Windows

You will need a service manager. For this tutorial we will use the Non-Sucking Service Manager. Go to their website and download the executables or build them yourself using the source. You will get an executable called "nssm.exe".

Open a command prompt (hit Win+R on your keyboard, then type cmd and click OK/Enter), then type:

cd c:\path\to\nssm
nssm install nameOfYourService

This will bring up an installation window, where you write the configuration.

Those are the important options. Click OK to install the service.

To start the service, find it in Windows service manager (hit Win+R, type: services.msc and click OK/Enter), or type "net start nameOfYourService" in the command prompt.

Your Node.JS script will then run as a service and startup after reboot. And run even if you are not logged in!

Start after another service has started

Make sure you add anything your script depends on as a service dependency. Lets say your node script access a mySQL server, then add mySQL as a dependency. Then Windows will make sure mySQL always starts before your script runs.

This can be done both from NSSM and the dependency tab in Windows service manager (services.msc).

Run code before the service is stopped

Windows will send a "SIGINT" to your script to make it stop, then give it a few seconds before it's killed completely. You can capture the "SIGINT" in your NodeJS script and make a clean exit.

process.on("SIGINT", function () {
	console.log("Received SIGINT");
	
	// Inform all connected players !?
	
	// Save !?
	
	process.exit();
});


Written by Johan Zetterberg April 17th 2015.


Follow me via RSS:   RSS https://z├Ąta.com/rss_en.xml (copy to feed-reader)
or Github:   Github https://github.com/Z3TA