You Don't Know Node.js EventLoop

Nairi

Harutyunyan

nairi.haroutiounian@gmail.com

@nairihar

#jsconfam18

  • Event Loop
  • Deep Dive into Libuv
  • Macrotasks
  • Microtasks
  • Threads
  • Why use Promise libs

Content

Node.js is a JavaScript runtime built on

Chrome's V8 JavaScript engine.

Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient.

What is Node.js

Reactor Pattern
event-driven model

I/O request

Event Loop

Event

Demultiplexer

Event

Queue

Hardware

I/O

Enqueue Event

Execute Event Handler

> fs.readFile('./file.txt', cb);

> uv__fs_read(req)

> cb(null, data);

Your Code

V8

operating system

C++ Bindings

Core Modules

libuv

c-ares,
zlib,
etc...

Node.js architecture

Macrotasks

Timers

I/O

Immediate

close events

process.exit

index.js

Event Loop

refs++

refs--

refs==0

refs=0

refs>0

Microtasks

Timers

I/O

Immediate

close events

process.exit

index.js

Event Loop

process.nextTick

Promise

Promise

nextTick

Timers

I/O

Timers

I/O

Immediate

close events

process.exit

Event Loop

index.js

process.nextTick

Promise

Promise

nextTick

Timers

I/O

Immediate

close events

process.exit

Event Loop

index.js

timers

I/O Poll

pending I/O callbacks

idle handlers

prepare handlers

Check handlers

Close handlers

Run expired timers

Run completed I/O handlers

Wait for I/O to complete

Some checking after polling

Run close handlers

libuv

JavaScript

Finished I/O work or I/O Errors

setTimeout
setInterval

 

setImmediate

.on('close'... handlers

epoll

kqueue

event ports

Thread Pool

linux

BSD

SunOS

IOCP

Windows

Network I/O

File I/O

DNS

...

libuv

Non-Blocking I/O

Blocking I/O

Threads

UV_THREADPOOL_SIZE=8 (SIZE<=128)

Thread pool

Blocking I/O

CPU intensive

Why use custom

Promise libs

Why not native

Timers

I/O

Immediate

close events

process.exit

Event Loop

index.js

Native Promise

Bluebird

Promise queue

Immediate queue

event in queue

callback

Summary

Node.js

libuv

c-ares

zlib

OpenSSL

http-parser

V8

npm

gyp

gtest

Queue

Timers

I/O

Immediate

close events

libuv

macrotask

Node.js

process.nextTick

Promise

Promise

nextTick

microtask

Thank You!

nairi.haroutiounian@gmail.com

@nairihar

#jsconfam18

Made with Slides.com