How to create threads in nodejs How to create threads in nodejs multithreading multithreading

How to create threads in nodejs


Every node.js process is single threaded by design. Therefore to get multiple threads, you have to have multiple processes (As some other posters have pointed out, there are also libraries you can link to that will give you the ability to work with threads in Node, but no such capability exists without those libraries. See answer by Shawn Vincent referencing https://github.com/audreyt/node-webworker-threads)

You can start child processes from your main process as shown here in the node.js documentation: http://nodejs.org/api/child_process.html. The examples are pretty good on this page and are pretty straight forward.

Your parent process can then watch for the close event on any process it started and then could force close the other processes you started to achieve the type of one fail all stop strategy you are talking about.

Also see: Node.js on multi-core machines


There is also at least one library for doing native threading from within Node.js: node-webworker-threads

https://github.com/audreyt/node-webworker-threads

This basically implements the Web Worker browser API for node.js.


From Node 10.5 there is now multi threading support, but it is experimental. Hope this will become stable soon.

Checkout following resources :


Update:

From Node v11.7.0 onward, you do not have to use --experimental-worker flag.

Release note: https://nodejs.org/en/blog/release/v11.7.0/