Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I pass a variable from parent to forked child process?

My parent process forks the child as so:

child = new fork('child.js');

Now in my parent process, I have a variable that contains an array. I want to pass this array to the child process so I have tried to send the variable as a message to the child:

//in parent.js
var jData = ['pro1', 'pro2', 'pro3']
child.send({'koota': jData})
//


//in child.js
process.on('koota', (jData) => {
    console.log(jData + ' from child!')
})
//

However, this does not work. What method is there to pass the array to the child so I can use it’s contents?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use process.on('message', () => {}) to receive messages that have been sent with child.send({}).

Adapted from the linked documentation page (shortened, see original for full example):

const { fork } = require('child_process');
const child = fork('child.js'); // no need for 'new'
const jData = ['pro1', 'pro2', 'pro3'];
child.send({'koota': jData});

child.js:

process.on('message', (msg) => {
    if (msg.koota) {
        console.log(msg.koota, 'from child!');
    }
});

You are currently using process.on(<a custom name, not "message">). You can simply check what ‘type’ of message you receive in the event handler:

process.on('message', (msg) => { 
  if (msg.koota) {
    // ...
  }
})

Sending a message like {type: 'koota', data: {}} would probably look nicer (if(msg.type === 'koota') {...}).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading