I was perusing some answers but they were very old. Does somebody know about the latest development in this regard?
Also is there any chance that JS will become multi-threaded in the near future?
Related Question:- link
The only way I know how to access a separate thread is to use Web Workers.
You can either create a file for the worker:
/////////////////////////////////////////// Main (main.js)
const worker = new Worker('worker.js')
// Set up a listener for messages from the worker
worker.onmessage = (message) => {
// This is where you receive your worker response
}
// Error handling
worker.onerror = console.error
// This message will be passed to the worker
worker.postMessage('hello worker')
/////////////////////////////////////////// Web workers (worker.js)
self.onmessage = (message) => {
// message.data is where your passed parameter is stored
const data = message.data
// Execute some code
// Send back a response to the main thread (main.js)
postMessage(data)
}
Or you can actually create a dynamic worker:
// main.js
// This function will be passed into the worker
function test(message) {
const data = message.data
// Response
postMessage(data)
}
// Dynamic creation of a worker
const bytes = new TextEncoder().encode(`self.onmessage = ${test.toString()}`)
const blob = new Blob([bytes], {type: 'application/javascript'})
const url = URL.createObjectURL(blob)
const worker = new Worker(url)
// Set up a listener for messages from the worker
worker.onmessage = (message) => {
// This is where you receive your worker response
}
// Error handling
worker.onerror = console.error
// This message will be passed to the worker
worker.postMessage('hello')
And 3rd variant is to use my own npm library @a4turp/threads.js
API is easy to use.
import Threads from '@a4turp/threads.js'
// Creating new threads
const threads = new Threads(4)
// Task to execute on separated threads
function test(param) {
param = param ?? 0
// Note that passed message is directly accessible. So no `message.data`
// Execute some code
// Just a regular return to get the message
return param + 10
}
// @param task: Function to execute
// @param message?: Parameter value of the function
// Chainable
threads.push(test, 20).push(test, 10).push(test)
// Execution
// You will get all responses in the same order you pushed tasks
const result = await threads.execute()
JS in majority of browsers run on V8, which is essentially same engine used by Node.js
The very foundation of Node.js and the way it works is it has Event Loop on single thread - which is intentional. It removes any issues with synchronizations between threads and any overhead with creating/deleting threads. That is very important concept for backend as it often handles tens or hundreds of concurrent requests at once.
It makes also code very deterministic (you know that the synchronous part of the code taken by Event Loop will be executed fully before another event in Event Loop will be taken and processed)
However from the beginning - Node.js HAS thread pool. Another threads are used for I/O operations in background (like requests or handling files). You can create workers which does have their own threads if you like to.
Does the core of Node.js change? Most likely not, it would be breaking change and it would be actually against the main idea of Node.js. Also not bringing much benefits (as you can use more threads if you really want to already)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With