Sending data to PM2 process using programatic API
Asked Answered
T

1

7

I'm trying to send data from a my main app to a child process. I've tried a few different alternatives but I'm currently stuck. Advice or pointers is very much appreciated.

I'm following the documentation at http://pm2.keymetrics.io/docs/usage/pm2-api/

index.js:

var pm2 = require('pm2');
var processName = "pm2_app";


console.log("hello world!");
pm2.connect(function(err) {
  if (err) {
    console.error(err);
    process.exit(2);
  }

  pm2.start({
    script    : "pm2_app.js"   // Script to be run
  }, function(err, apps) {

    if(err) {
      console.log(err);
    }
    console.log("app started!");
    pm2.list(function(err, list) {
      console.log("Child process started with pid: " + list[0].pid);
      pm2.sendDataToProcessId({
          type : 'process:msg',
          data : {
            some : 'data',
            hello : true
          },
          id   : list[0].pid
        },
        function(err, res) {
          console.log(err);
          console.log("message sent");
        });

      pm2.disconnect();

    });
  });
});

pm2_app.js:

var start = Date.now();

setInterval(function(){
    console.log(Date.now() - start);
}, 1000);

process.on('message', function(packet) {
    console.log("got message from mr. Rabbit");
    console.log(packet);
});
Taciturnity answered 18/2, 2016 at 10:23 Comment(1)
try: process.on('process:msg', ....)Gerbil
T
11

This solution provided by @chrizz1001 worked in the end:

index.js

var pm2 = require('pm2');

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

  pm2.start({
    script    : "pm2_app.js"   // Script to be run
  }, function(err, apps) {

    if(err) {
      console.log(err);
    }
    console.log("app started!");
    pm2.list(function(err, list) {

      pm2.sendDataToProcessId(list[0].pm2_env.pm_id, {
          type : 'process:msg',
          data : {
            some : 'data',
            hello : true
          },
          topic: "my topic"

        },
        function(err, res) {
          console.log(err);
        });

      pm2.disconnect();
    });
  });
});

pm2_app.js:

var start = Date.now();

setInterval(function(){
    console.log(Date.now() - start);
}, 1000);

process.on('message', function (data) {
   console.log('your actual data object', data.data);
});

What made the trick is two things:

  • with id it means PM2 id, not system/OS pid
  • Note that the id is an argument to the sendDataToProcessId(id, ...) and not part of the dictionary sent in
Taciturnity answered 19/2, 2016 at 11:36 Comment(1)
pm2.sendDataToProcessId use pm_id, not pidVolz

© 2022 - 2024 — McMap. All rights reserved.