This example demonstrates how NodeJS can use multiple threads for long running tasks. Use cases can be long running calculations, compressions or encryptions that should not block the main thread.
- NodeJS 10.x or NodeJS 12
npm installnpm run buildnpm start
During the execution the index script calls the worker script and prints each second a log message to the console. In the meanwhile the worker is doing some simple calculations that cost some time. When the worker is done, the interval of log messages is stopped and the result of the sum is printed out.
[1s] Worker is working...
[2s] Worker is working...
[3s] Worker is working...
[4s] Worker is working...
[5s] Worker is working...
[6s] Worker is working...
[7s] Worker is working...
[8s] Worker is working...
[9s] Worker is working...
[10s] Worker is working...
[11s] Worker is working...
[12s] Worker is working...
[13s] Worker is working...
[14s] Worker is working...
[15s] Worker is working...
[16s] Worker is working...
[17s] Worker is working...
{ result: 5000000000, status: 'Done' }