In this article we will learn how to use node-windows to run NodeJS server as Windows service. Running NodeJS application as Windows service helps us pass the maintenance part of service to Windows. The service now can be set to auto restart if Windows restarts or there is crash in service due to any reason.
There are many libraries or utilities that can help you one of the easiest one is node-windows. You may install a NodeJS script that runs as Windows service. There are more things that the module helps you with but we will just see the install and start part of it.
Installation
As it is a NodeJS package you can easy install it globally or locally using npm command.
With global flag:
npm install -g node-windows
Locally with out global flag
npm install node-windows
Service
There is a Service function using which we can create a wrapper around our NodeJS server and install it as a service. Note that creating a service requires administrative privileges and you may be prompted to provide one once you run the below script. e.g.
const Service = require('node-windows').Service;
// Create a new service object
const nodeJSServer = new Service({
name:'<Application Name displayed in services list>',
description: '<Application Description displayed in services list>',
script: 'C:\\path\\to\\NodeJSServer.js',
nodeOptions: [
'--harmony',
'--max_old_space_size=4096'
]
//, workingDirectory: '...'
//, allowServiceLogon: true
});
// Listen for the "install" event and
// start the our NodeJS server as service
nodeJSServer.on('install',function(){
nodeJSServer.start();
});
// Initiate the installation of our service
nodeJSServer.install();
WindowsServiceWrapperScript.js
So suppose we have our NodeJS server located at C:\sampleApplication and you are running it as:
C:\sampleApplication > node server.js
Then you may change the script attribute as below and make this server service run as Windows service
script: 'C:\\sampleApplication\\server.js',
Run Nodejs Server as Windows service
Now our Windows wrapper script is ready, just run it as below:
node WindowsServiceWrapperScript.js
That’s it to verify if the service is running open services application by running the command services.msc in windows run prompt. The prompt appears when you press WIN + R command.
Hope this helps you to understand how easily we can write a wrapper around our server code and make it run as Windows service.