How To Create Nwjs Desktop App Auto Restart

Posted By : Vivek Joshi | 29-Jan-2018

For creating any desktop/web application auto-restart using nwjs (nodeJS) we require the PM2(process manager ) which will use to watch our application process and auto restart it if it stops.

For implementing it to your nodejs web/desktop application following steps are required.

 

step1:- Install the pm2 module.

npm install pm2 --save

 

step2:- After installing the pm2 module we need to connect pm2 with our application and add the script which will be run if our application is killed.

var pm2 = require('pm2');
pm2.connect(noDemonMode, function (err) {
   
    if (err) {
      console.error(err);
      process.exit(2);
    }

    pm2.start({
       name: 'applicationName',
      script: 'path/to/your/application', // Script to be run
      exec_mode: 'fork', 
      instances: 1, 
      
    }, function (err, apps) {
      if (err) throw err
    });
  });

noDemonMode is a boolean value(true/false) if you want the pm2 not be run as a daemon and will die when the application exits. By default, pm2 stays alive after your script exits.

start function of pm2, if pm2 is already running your application will link to the pm2 process.

if you are using nwjs desktop application you can enter the name to your application name and in the script, you can enter the executable file path which you want to execute.

if you are using nodejs application then enter the stating nodejs file path of your application (e.g app.js).

 

Step 3:- There is lots of more configuration instance of pm2 in nodejs which can be used for the delay and wait for restart your application and there is a log of other function through which you can maintain your application.

 

pm2.connect(function (err) {
   
    if (err) {
      console.error(err);
      process.exit(2);
    }

    pm2.start({
      // name: 'appName',
      script: 'path/to/your/application', // Script to be run
      exec_mode: 'cluster', // Allows your app to be clustered 
      instances: 1, // Optional: Scales your app by 1
      wait_ready:true,
      restart_delay: 10000,
      listen_timeout:10000,
       restart_delay:10000,
	interpreterArgs:'node',
	cwd:'path of script file',//set path of you application whic you want to restart
	autorestart:true, //auto start default(true) if false it will not restart you application automatically.
       max_memory_restart: '100M' // Optional: Restarts your app if it reaches 100Mo
    }, function (err, apps) {
    
     
      if (err) throw err
    });
  });

For add more configuration and functions you can visit Here 

 

About Author

Author Image
Vivek Joshi

Vivek is Web App Developer in Java Technology and also working on NodeJS.

Request for Proposal

Name is required

Comment is required

Sending message..