javascriptnode.jsevent-looplibev

Nodejs Event Loop


Are there internally two event loops in nodejs architecture?

On an I/O request does node queue the request to libeio which in turn notifies the availability of data via events using libev and finally those events are handled by v8 event loop using callbacks?

Basically, How are libev and libeio integrated in nodejs architecture?

Are there any documentation available to give a clear picture of nodejs internal architecture?


Solution

  • I have been personally reading the source code of node.js & v8.

    I went into a similar problem like you when I tried to understand node.js architecture in order to write native modules.

    What I am posting here is my understanding of node.js and this might be a bit off track as well.

    1. Libev is the event loop which actually runs internally in node.js to perform simple event loop operations. It's written originally for *nix systems. Libev provides a simple yet optimized event loop for the process to run on. You can read more about libev here.

    2. LibEio is a library to perform input output asynchronously. It handles file descriptors, data handlers, sockets etc. You can read more about it here here.

    3. LibUv is an abstraction layer on the top of libeio , libev, c-ares ( for DNS ) and iocp (for windows asynchronous-io). LibUv performs, maintains and manages all the io and events in the event pool. ( in case of libeio threadpool ). You should check out Ryan Dahl's tutorial on libUv. That will start making more sense to you about how libUv works itself and then you will understand how node.js works on the top of libuv and v8.

    To understand just the javascript event loop you should consider watching these videos

    To see how libeio is used with node.js in order to create async modules you should see this example.

    Basically what happens inside the node.js is that v8 loop runs and handles all javascript parts as well as C++ modules [ when they are running in a main thread ( as per official documentation node.js itself is single threaded) ]. When outside of the main thread, libev and libeio handle it in the thread pool and libev provide the interaction with the main loop. So from my understanding, node.js has 1 permanent event loop: that's the v8 event loop. To handle C++ async tasks it's using a threadpool [via libeio & libev ].

    For example:

    eio_custom(Task,FLAG,AfterTask,Eio_REQUEST);
    

    Which appears in all modules is usually calling the function Task in the threadpool. When it's complete, it calls the AfterTask function in the main thread. Whereas Eio_REQUEST is the request handler which can be a structure / object whose motive is to provide communication between the threadpool and main thread.