Skip to content

Instantly share code, notes, and snippets.

@dan-king
Created January 22, 2018 19:36
Show Gist options
  • Save dan-king/3b213bfc1774494b217b449e67d3f267 to your computer and use it in GitHub Desktop.
Save dan-king/3b213bfc1774494b217b449e67d3f267 to your computer and use it in GitHub Desktop.
Steps for setting up a Node.js application as a service on Windows

Steps for setting up a Node.js application as a service on Windows

Step 1

Install node-windows:

npm install -g node-windowsremoveNodeWindowsService

Step 2

Link your project to node-windows.

In your project root, run:

npm link node-windows

Step 3

Create and run the following JavaScript:

e.g. File name: createNodeWindowsService.js

var Service = require('node-windows').Service
 
// Create a new service object 
var svc = new Service({
  name:'The Name of Your App',
  description: 'The description of your application.',
  script: 'C:\\path\\to\\your\\app\\index.js',
  env: {
    name: "OPTIONAL_ENVIRONMENT_VARIABLE",
    value: "C:\\path\\to\\your\\optional\\config\\file\\index" // Note: Do NOT include '.js' in the file name. 
  }
})

// Listen for the "install" event, which indicates the process is available as a service. 
svc.on('install',function(){
  console.log('Service installed. Starting service...')
  svc.start()
  console.log('The service exists: ',svc.exists)
})
 
svc.install()

Execute the file from command line, e.g.:

node createNodeWindowsService.js

Remove Service

To remove the windows service create and run the following JavaScript:

e.g. File name: removeNodeWindowsService.js

var Service = require('node-windows').Service
 
// Create a new service object 
var svc = new Service({
  name:'The Name of Your App',
  script: 'C:\\path\\to\\your\\app\\index.js',
  env: {
    name: "OPTIONAL_ENVIRONMENT_VARIABLE",
    value: "C:\\path\\to\\your\\optional\\config\\file\\index" // Note: Do NOT include '.js' in the file name. 
  }
})

// See https://github.com/coreybutler/node-windows/issues/51
svc._directory = 'C:\\apps\\app-user-dashboard\\';

// Listen for the "uninstall" event, which indicates the 
// process is available as a service. 
svc.on('uninstall',function(){
  console.log('Uninstall complete.')
  console.log('The service exists: ',svc.exists)
})
 
// Uninstall the service. 
svc.uninstall()

Execute the file from the command line, e.g.:

node removeNodeWindowsService.js
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment