Node.js: Application as a Windows service

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.

React: build for relative paths

If it’s not a real production build, you probably test your React Apps in a sub folder at your hosting space. The information on this is scattered and explained way too difficult. There’s nothing to it:

  1. Open package.json in uour App root folder
  2. Find the parameter “homepage” or add it (image above)
  3. Give the parameter the value of the complete path where your app will be hosted (image above)
  4. Save the package.json file
  5. Build the React app using npm start build
  6. Upload the production build (folder build) to your hosting provider
  7. And done!

And when you are building the React App using npm run build, it should confirm the subfolder: