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

Time:12-10

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?

CodePudding user response:

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') {...}).

CodePudding user response:

I think you can find what you need here.

  • Related