Reputation: 11071
Based on my understanding, only I/O in NodeJS is non-blocking. If we do, for example, lots of heavy math operations, other users cannot access to the server until it's done.
I was wondering if there is a non-blocking way to do heavy computation in NodeJS? Just curious.
Upvotes: 14
Views: 4218
Reputation: 11
I would use JXCore - it's a polished nodejs based engine which runs your code but has several options including the multi threading you are searching for. Running this in production is a charm! Project's source: https://github.com/jxcore/jxcore
Features include:
Upvotes: 0
Reputation: 933
You can use node cluster module.
https://nodejs.org/api/cluster.html
Upvotes: 0
Reputation: 161617
If you have long-running calculations that you want to do with Node, then you will need to start up a separate process to handle those calculations. Generally this would be done by creating some number of separate worker processes and passing the calculations off to them. By doing this, you keep the main Node event loop unblocked.
On the implementation side of things, you have two main options.
I'd go with option one now. The current child process APIs support sending messages and objects between processes easily in a worker-like way, so there is little reason to use a separate worker module.
Upvotes: 9
Reputation: 1254
You can use Hook.io to run a separate node process for your heavy computation and communicate between the two. Hook.io is particularly useful because it has auto-healing meshes meaning that if one of your hooks (processes) crashes it can be restarted automatically.
Upvotes: 2
Reputation: 133
I think this is way to late, but this is an awesome feature of nodejs you've to know about.
The only way abot multithreading is by spawning new processes, right so far. But nodejs has an implemented message feature between spawned node-forks. http://nodejs.org/docs/latest/api/child_processes.html#child_process.fork Great work from the devs, you can pass objects etc. as message to your childs and backwards
Upvotes: 0
Reputation: 13677
Use multiple node instances and communicate over node-zeromq, HTTP, plain TCP sockets, IPC (e.g. unix domain sockets), JSON-RPC or other means. Or use the web workers API as suggested above.
The multiple instances approach has its advantages and disadvantages. Disadvantages are that there is a burden of starting those instances and implementing own exchange protocols. Advantages are that scaling to many computers (as opposed to many cores/processors within a single computer) is possible.
Upvotes: 1
Reputation: 1700
Use multiple NodeJS instances and communicate over sockets.
Upvotes: 1