Source: pm2utils.js

/**
 * @module pm2utils
 */

var pm2 = require('pm2');
var async = require('async');

/**
 * Wrapper around very fragile pm2 API function to isolate logic
 *
 * As of 1.0.0, documentation for sendDataToProcessId is almost nonexistent, and
 * what documentation exists is entirely wrong. This function exists solely to separate this
 * likely-deprecated API call from its parent routine.
 *
 * @param id process id (pm_id)
 * @param data data object to pass to sub process
 * @param cb
 * @private
 */
var _sendData = function(id, data, cb){
    pm2.sendDataToProcessId(id, {
        topic : 'process:msg',
        data : data,
        id   : id
    }, function(err, res){
        if (err){
            console.log(err);
        }
        if (cb) return cb(err, res);
    });
};

/**
 * Gets all active pm2 processes for given processname and passes data object to them
 * over 'process:msg' topic
 *
 * @param processname name of running pm2 process. All processes running under this processname
 *      will be affected
 * @param data Object to pass to processes
 * @param cb callback function takes (err, responses), where responses is array of strings representing
 *      response objects from processes.
 * @type {Function}
 */
exports.sendDataToProcessName = function(processname, data, cb){
    function _handleError(err){
        console.log(err);
        cb(err);
        pm2.disconnect();
    }
    pm2.connect(function(err){
        if (err) return _handleError(err);
        pm2.list(function(err, list){
            if (err) return _handleError(err);
            var responses = [];
            async.each(list, function(process, callback){
                if (process.name === processname){
                    var id = process.pm2_env.pm_id;
                    _sendData(id, data, function(err, res){
                        var response = 'Message sent to pm2 pm_id ' + id + '. Received response: ' + JSON.stringify(res);
                        responses.push(response);
                        callback(err);
                    });
                }
            }, function(err){
                if (err) return _handleError(err);
                pm2.disconnect();
                if (cb){
                    cb(null, responses);
                }
            });
        });
    });
};