Search code examples
node.jspm2

pm2 - How can I get/access process status programmatically?


I am trying to write a simple server that can communicate the status of processes. I understand how i can use the pm2 package and send that data as a response. Essentially, I am trying to build a simple web UI to monitor a remote process.

The issue that I am having is:

  • When I call pm2.list() or pm2.jlist(), the methods execute fine, and I can see the output in my pm2 log file, but the server doesnt send any data back
  • When the above works, pm2 also restarts the the app, and I can see my restart count going up.

Is this possible?

Here is my app code:

const express = require('express');
const pm2 = require('pm2')

const app = express();
const { PORT = 3000 } = process.env;

app.get('/', (req, res) => {
  console.log('foo');
  pm2.describe((process, err) => {
    res.send(process)
  })
});


app.listen(PORT, () => {
  console.log(`Listening on port ${PORT}`);
});

pm2 json file

{
  "name": "testPm2app",
  "script": "1.js",
  "watch": true,
  "ignore_watch": "node_modules"
}

Solution

  • Your use of pm2.describe is incorrect. The first parameter should be the process name or the ID of the process. You can attach a callback function to the second parameter that will be executed with process data. Look into the below code.

    const express = require('express');
    const pm2 = require('pm2')
    
    const app = express();
    const { PORT = 3000 } = process.env;
    
    app.get('/', (req, res) => {
      console.log('foo');
      pm2.describe('testPm2app', (err, data) => {
        if(err) {
            res.status(500).end();
        }
        res.send(data);
      })
    });
    
    
    app.listen(PORT, () => {
      console.log(`Listening on port ${PORT}`);
    });