I am trying to develop an app on ElectronJS, and a core part of the app is doing CPU intensive tasks which as we all know are blocking processes. Can someone suggest me some resources to tackle this? What are the best practices for such situtations?
I recommend taking a look at the cluster module. It allows you to create a worker process, which does not block your main program (see code example below). For additional speed, you may use WASM or FFI via Rust or C++ or any other language which can be compiled to it.
The alternative would be to write a binary which is called by your main process, however that requires binaries for each platform you distribute to, which might not be what you want.
// index.js
const cluster = require('cluster');
if (cluster.isMaster) {
// execute you main program
require('main.js');
}
else {
// execute worker program
require('worker.js');
}
// main.js
const cluster = require('cluster');
// create new worker process
const worker = cluster.fork();
// handle messages from the worker
worker.on('message', msg => {
console.log(msg.cmd, msg.payload);
});
// send command to worker
worker.send({ msg: 'sum', payload: [1, 2, 3] });
// worker.js
// handle messages from the main process
process.on('message', msg => {
switch(msg.cmd) {
case 'sum':
const result = msg.payload.reduce((num, sum) => sum + num, 0);
// send reply to main process
process.send({ cmd: msg.cmd, payload: result });
break;
}
});
I guess you could write that CPU intensive code in C++/Go/Rust etc and then just call its binary from your electron app. If you're feeling smart, maybe try FFI
Lorefnon
Open Web Enthusiast
You can move your task to a web-worker, so your CPU intensive tasks don't block the main thread.
Workers are not difficult to use by themselves, but libraries like greenlet (useful for very small functions), comlink (Bidirectional RPC between worker and main thread) and clooney (Actor library built on top of comlink) can make application code a lot simpler.
I recently wrote a post about integrating comlink, worker-loader and typescript.