How to leave the NodeJS running as a service? [duplicate]

0

I was giving a search here and found only solutions for linux , leaving the server running at dos is not safe, because at any moment there might be a fall.

The question is, is there any method to let NodeJS run as serviço ? And if the server crashes, is there a way to automatically "restart" it?

    
asked by anonymous 19.02.2018 / 17:41

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 reboot, it was already, your site will stay off the air until you run npm start again.

For this 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, inside your Node.js project (in the root) create a service.js file 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 to your liking, but watch out for the script property in this code, which should contain the absolute path to the JS file that launches your application. In my case, as I'm using express, I'm pointing to the www file that is in the bin folder of the project (interestingly it has no extension, but it's a file).

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

If you need to remove this service (to install a more upgraded version, for example), run the command below in cmd :

SC STOP servicename
SC DELETE servicename

I hope it helps:)

    
19.02.2018 / 17:41