Take this brief example: I have a file called parent.js
, with the following code:
var child_process = require('child_process')
var forker = child_process.fork(__dirname + '/child.js')
forker.on('message', function (msg) {
console.log('PARENT got message:', msg)
})
// sends a message to the forked process?
forker.send({msg: 'Parent message.'})
First question: am I getting this right? child_process.fork()
returns the forker process, doesn't it? (like child_process.spawn()
?)
Anyway, here's the code for child.js
:
process.on('message', function (msg) {
console.log('CHILD got message:', msg)
})
// sends a message to the forker process? why?
process.send({msg: 'Message from the child.'})
Second question: what does process
refer to inside the child process? To the current forked process I guess? If so, when I call process.send()
I'm sending a message to the parent process right?
Third question: take this example (simplified version from Node: Up and Running):
var cluster = require('cluster')
if (cluster.isMaster) {
// fork child...
var worker = cluster.fork()
worker.on('message', function (msg) {
// do stuff
})
} else if (cluster.isWorker) {
process.send(aMessage)
}
What I find unclear is: worker
is kind of the forker
of the previous example? And process.send()
inside the worker sends a message to the forker process?