목회칼럼

Node.js Event Loop: Understanding How Async Works

페이지 정보

작성자 Harry Piesse
작성일

본문


Node.js event loop enables non-blocking I/O despite single-threaded JavaScript. The event loop phases include timers, pending callbacks, idle/prepare, poll, check, close. Timers phase executes setTimeout and setInterval callbacks. Pending callbacks phase handles I/O callbacks deferred to next iteration. Poll phase retrieves new I/O events and executes their callbacks. Check phase runs setImmediate callbacks. Close phase executes close event callbacks like socket.on('close'). process.nextTick callbacks run between phases, not within phases. Microtasks (Promise callbacks) run after each phase. Blocking the event loop with CPU-intensive operations degrades performance. Worker threads handle CPU-intensive tasks without blocking. Understanding event loop phases helps debug async issues. setImmediate vs setTimeout(fn, 0): setImmediate runs in check phase, setTimeout in timers phase. Unref methods prevent timers from keeping process alive. Error handling requires proper promise rejection handling. The event loop makes Node.js efficient for I/O-bound applications. libuv library implements the event loop in C++. Node.js event loop differs from browser event loop. Mastering the event loop is essential for Node.js .

관련자료