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);
});
js Process with PM2 API. PM2 is a production process manager for Node. js applications with a built-in load balancer. It allows you to keep applications alive forever, to reload them without downtime and to facilitate common system admin tasks.
The solution is to create a PM2 group and a common configuration directory. Next, assign deploy user and your main account to this group. Lastly, change the ownership of the configuration directory for the PM2 group and set environment variable to use the new path for this directory while executing PM2 commands.
PM2 is a battle tested, production ready runtime and process manager for Node. js applications. It comes with a built-in load balancer, as well, which makes scaling applications even easier.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With