Node being single threaded is a common misconception. The truth is much more complex. While the Node Event Loop is single threaded, some of the functions included in the Node standard library are not single threaded.
Some of the functions included inside of Node that we run are running outside the Event Loop and therefore outside that single thread.
So a lot of the code we write in Node does not execute inside that Single Thread entirely.
You can test this out for yourself by writing code that gives you real proof that not all of Node is truly single-threaded by implementing the pbkdf2
function from the crypto
module.
You can benchmark how long the pbkdf2
function takes to run to get a sense of how threading and threadpools actually are working on your machine. So you can create various pbkdf2
functions to represent the threads. The function will do some expensive work and you can benchmark that and use it to detect whether Node is single threaded like so:
const crypto = require('crypto');
const start = Date.now();
crypto.pbkdf2('a', 'b', 100000, 512, 'sha512', () => {
console.log('1:', Date.now() - start);
});
This function takes quite awhile to run, so about 1 second in most mid-2015 MacBook Pros.
So the callback function above is computing a hash which again with the machine I indicated above should take no more than 1 second to complete, but what the function does is not as important as how long it takes to execute on your machine.
You can add more function calls to represent more threads and you can also tweak the threadpool size in your machines threadpool like so process.env.UV_THREADPOOL_SIZE = 2;
.