How do I get Nodejs running as a service?

Asked

Viewed 3,794 times

0

I was doing some research around here and found only solutions for linux, let the server run by dos it’s not safe, because at any time there could be a fall.

The question is, is there any method to leave the NodeJS running as serviço? And if the server falls, there is a way for it to "restart" automatically?

1 answer

0


The solution to this is called : Windows Service

By default, your Node.js site will run while the console window that started your site is running. If you close it, or your server restarts, it’s gone, your site will stay down until you run npm start again.

In order for this not to happen, you must install your site as a Windows Service. To do this, first install the Node-windows module globally:

npm install -g node-windows

Now run the following command (within the folder of your project) to include a reference of this module to your project:

npm link node-windows

Then, within your Node.js project (at the root) create a file service.js with the following content:

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

// Create a new service object
var svc = new Service({
  name:'Nome da sua Aplicação',
  description: 'Apenas uma descrição',
  script: 'C:\\domains\\sitenodejs\\bin\\www'
});

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

svc.install();

Change the name and Description properties according to your taste, but watch out for the script property in that code, which should contain the absolute path to the JS file that starts your application. In my case, as I am using express, I am pointing to the www file that is in the bin folder of the project (interestingly it has no extension, but it is a file).

If you did everything right, go to Ferramentas Administrativas > Serviços (Administrative Tools > Services or services.msc in Windows Run/Run) and your service will appear there with the name you set there in the script, allowing you to change your startup settings, give Start, Stop, etc.

If you need to remove this service (to install an updated version, for example) turn the command below on cmd:

SC STOP servicename
SC DELETE servicename

I hope it helps :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.