Search code examples
javascriptnode.jscallstackevent-looplibuv

LibUV NodeJS handle synchronous or asynchronous tasks?


I'm Nodejs beginner. I have been reading some documents and posts on Google and as far as I know, LibUV is used to handle asynchronous tasks. However, when I came across a post recently, the author mentioned that LibUV is used to offload synchronous operations. (https://dev.to/johnjardincodes/increase-node-js-performance-with-libuv-thread-pool-5h10 )

Libuv initiates a thread pool of 4 threads that it uses to offload synchronous operations to. In doing this, Libuv ensures that our application does not get blocked unnecessarily by synchronous tasks.

This has left me confused. Does this mean that synchronous tasks will be executed simultaneously in LibUV and the results will be returned to the main stack? Can someone please help me understand this better? Thank you !


Solution

  • Please have a look at this talk: What the heck is the event loop anyway?. And check this page from Node.js documentation. To see how Node.js uses libuv.

    As per libuv's documentation it uses a thread pool of size 4 by default:

    libuv provides a threadpool which can be used to run user code and get notified in the loop thread. This thread pool is internally used to run all file system operations, as well as getaddrinfo and getnameinfo requests.

    Its default size is 4, but it can be changed at startup time by setting the UV_THREADPOOL_SIZE environment variable to any value (the absolute maximum is 1024).

    Which means that when you perform an HTTP call with request.get('URL', cb); for example. The protocol itself is synchronous as you will send a request and wait for the response. But the Node.js APIs (libraries) expose asynchronous functions. It will push your Network I/O operations to libuv which reports back to your main Node.js thread once your response is resolved (or timed out). While your network operations are being resolved outside JavaScript (thanks to libuv), you continue executing the rest of your JavaScript code. And your callback (cb in my example) will be pushed to a queue and only pulled to the call stack when you get something back from C libraries running under the hood.

    JavaScript is synchronous by default and is single-threaded. That's why Node.js's V8 implements libuv library to handle most of the I/O operations which are expensive and sometimes blocking.

    Read more: