Friday, May 26, 2017

Merging/namespacing PM2 apps

Leave a Comment

There is PM2 configuration, /home/foo/someconfig.json

{     "apps": [         {             "name": "foo-main",             "script": "./index.js",         },         {             "name": "foo-bar",             "script": "./bar.js"         },         {             "name": "foo-baz",             "script": "./baz.js"         }     ] } 

Most of the time I want to refer to all of the apps under current namespace, e.g.

pm2 restart foo 

instead of doing

pm2 restart foo-main foo-bar foo-baz 

Bash brace extension cannot be used because apps may run in Windows.

Doing pm2 restart /home/foo/someconfig.json isn't a good option, because it takes some time to figure out config file path, it may differ between projects and even change its location.

Can foo-* apps be merged into single foo app or be referred altogether in another reasonable way?

1 Answers

Answers 1

It seems that pm2 itself doesn't support wildcard-based restart, but it is not complex to make a simple script to do it using pm2 programmatic API.

Here is a working script that demonstrates the idea:

var pm2 = require('pm2');  pm2.connect(function(err) {   if (err) {     console.error(err);     process.exit(2);   }    pm2.list(function(err, processDescriptionList) {     if (err) throw err;     for (var idx in processDescriptionList) {       var name = processDescriptionList[idx]['name'];       console.log(name);       if (name.startsWith('foo')) {         pm2.restart(name, function(err, proc) {           if (err) throw err;           console.log('Restarted: ');           console.log(proc);         });       }     }   }); }); 

To make it fully functional, it is also necessary to pass foo as command-line argument (now it is hard-coded) and handle exit (now it works, but doesn't exit on finish).

Here is the full code example, including small sample apps and config.

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment