Node.js: Application as a Windows service

  • React

node-windows

node-windows is a standalone module that makes it possible to offer a Node.js script as native Windows services..

Prerequisite: You have succesfully installed Node.js.

Install with npm using the global flag:

npm install -g node-windows

In the project root run:

npm link node-windows

Hello world example

Create a hello.js file with this code (Hello World sample from the Express website):

const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => res.send('Hello World!'))

app.listen(port, () => console.log(`Example app listening at http://localhost:${port}`))

You can (should) test if it works by running it from the command line:

node hello.js

If there are no errors, point your browser to http://localhost:3000. If it says Hello World! you are well on your way!

Script to create the service

Now we have our app, we want to make it a service. This is achieved by another script we call hello-windows-service.js:

var Service = require('node-windows').Service;

// Create a new service object
var svc = new Service({
  name:'Node app hello',
  description: 'Node app hello as Windows Service',
  script: 'C:\\npm\\.node_modules_global\\hello.js'
});

// Listen for the "install" event, which indicates the
// process is available as a service.
svc.on('install',function(){
  svc.start();
});

svc.install();

Most important is the correct location of the script in the Service call..
Now run this script to install the service into Windows:

node hello-windows-service.js

Now if you check your services, I hope you’ll find this:

Great! The Node app is running as a Windows service under a local system account. The app is running even when nobody is logged in. Goal achieved. Oh and because it’s on Automatic start, it wil always become available after each server restart.

Based on this article by Peter Eysermans.

Leave a Reply

Your email address will not be published. Required fields are marked *