Set Up a Node.js Backend as a Windows Service

Gul Ershad
3 min readNov 17, 2024

--

In this article, we will walk through the process of setting up a Node.js backend as a Windows service, where we will minify and uglify our JavaScript files using Terser to optimize them for production. Then, we will use node-windows to create a Windows service that runs our Node.js application in the background without requiring an active terminal.

Key Steps:

  1. Minifying and Uglifying JavaScript Files using Terser.
  2. Creating a Windows Service to run the backend application.

Let’s dive into the details!

Minifying and Uglifying JavaScript Files

When preparing your Node.js backend for production, it’s essential to optimize the JavaScript files by minifying and uglifying them. This reduces the file size and makes it harder for anyone to read your code. To achieve this, we will use the Terser package, which is a popular JavaScript minifier.

Step 1: Install Dependencies

First, you need to install Terser. Run the following command to install it in your project:

npm install terser

Step 2: Create a Build Script

The build script will go through all JavaScript files in a src directory, minify and uglify them, and then save the minified versions to a ehrService directory.

Here’s a simple build.js script for minifying all .js files recursively:

const fs = require('fs');
const path = require('path');
const Terser = require('terser');

// Path to the source and dist directories
const srcDir = path.join(__dirname, 'src'); // Source directory containing JavaScript files
const distDir = path.join(__dirname, 'ehrService'); // Output directory for minified files

// Ensure dist directory exists
if (!fs.existsSync(distDir)) {
fs.mkdirSync(distDir);
}

// Minification function
async function minifyFiles() {
// Read all JavaScript files in the src directory
const filesToMinify = getAllFiles(srcDir);

for (const filePath of filesToMinify) {
const outputFilePath = path.join(distDir, path.relative(srcDir, filePath));
const fileContent = fs.readFileSync(filePath, 'utf8');

try {
// Minify the file content using Terser
const minified = await Terser.minify(fileContent, {
mangle: {
reserved: ['createApp', 'expressApp'], // Prevent mangling of these variables
},
compress: {
drop_console: true, // Optionally remove console logs
passes: 3, // More compression passes for better minification
},
output: {
beautify: false, // Don't beautify the output (uglify it)
comments: false, // Remove comments
},
});

if (minified.error) {
console.error('Error minifying file', minified.error);
} else {
// Ensure the corresponding folder exists in the dist directory
const distDirPath = path.dirname(outputFilePath);
if (!fs.existsSync(distDirPath)) {
fs.mkdirSync(distDirPath, { recursive: true });
}

// Save the minified content to the dist folder
fs.writeFileSync(outputFilePath, minified.code);
console.log(`Minified and uglified file saved to: ${outputFilePath}`);
}
} catch (err) {
console.error('Error during minification', err);
}
}
}

// Helper function to get all JavaScript files in the directory (recursively)
function getAllFiles(dirPath) {
const files = [];
const items = fs.readdirSync(dirPath);

items.forEach(item => {
const fullPath = path.join(dirPath, item);
const stat = fs.statSync(fullPath);

if (stat.isDirectory()) {
// If it's a directory, recurse into it
files.push(...getAllFiles(fullPath));
} else if (stat.isFile() && fullPath.endsWith('.js')) {
// If it's a JavaScript file, add it to the list
files.push(fullPath);
}
});

return files;
}

// Run the minification process
minifyFiles();

Creating a Windows Service for Node.js Application

Now that we have the minified JavaScript files, we can create a Windows service to run the Node.js application in the background.

Step 1: Install node-windows

npm install node-windows

Step 2: Create a Service Script

const path = require('path');
const Service = require('node-windows').Service;

// Create a new service object
const svc = new Service({
name: 'EHRService', // Name of the service
description: 'EHR Service running as a Windows Service.', // Description of the service
script: path.join(__dirname, 'ehrService', 'index.min.js'), // Path to your minified app (replace with your minified index.js)
});

// Event listener when the service is installed
svc.on('install', function () {
console.log('Service installed successfully!');
svc.start();
});

// Event listener when the service is uninstalled
svc.on('uninstall', function () {
console.log('Service uninstalled successfully!');
});

// Install the service
svc.install();

Running the Application

node build.js

Install the Windows Service

node service.js

Check the Service

node service.js uninstall

Conclusion

With the steps above, we successfully:

  1. Minified and uglified our Node.js application using Terser to make it production-ready.
  2. Created a Windows service using node-windows to run the backend application as a background process.

This approach ensures that your Node.js backend runs continuously without needing a terminal session open, and the JavaScript files are optimized for production. It’s a powerful solution for deploying a Node.js application as a Windows service.

--

--

Gul Ershad
Gul Ershad

Written by Gul Ershad

A technology explorer with the drive to learn, apply and expand his mind.

No responses yet