...

/

Using External Processes (II)

Using External Processes (II)

Learn how to prevent the event loop from blocking using external processes.

Let’s now implement the worker (our child process).

Note: It’s good to know that the send() method available on a child process instance can also be used to propagate a socket handle from the main application to a child process (look at the child_process documentation). This is actually the technique used by the cluster module to distribute the load of an HTTP server across multiple processes.

Implementing the worker

Let’s create the workers/subsetSumProcessWorker.js module, our worker process.

Press + to interact
import { SubsetSum } from '../subsetSum.js'
process.on('message', msg => { //(1)
const subsetSum = new SubsetSum(msg.sum, msg.set)
subsetSum.on('match', data => { //(2)
process.send({ event: 'match', data: data })
})
subsetSum.on('end', data => {
process.send({ event: 'end', data: data })
})
subsetSum.start()
})
process.send('ready')

We can immediately see that we’re reusing the ...