Câu hỏi phỏng vấn Nodejs
Câu hỏi

What's the Event Loop?

Câu trả lời

The Event Loop is a fundamental concept in Node.js that enables non-blocking I/O operations, allowing Node.js to perform asynchronous tasks such as reading from the filesystem, making network requests, and more. Despite JavaScript being single-threaded, the Event Loop facilitates concurrent operations by offloading operations to the system kernel whenever possible.

How the Event Loop Works

  1. Phases of the Event Loop:

    • Timers: Executes callbacks scheduled by setTimeout() and setInterval().
    • I/O Callbacks: Executes almost all callbacks with the exception of close callbacks, those scheduled by timers, and setImmediate().
    • Idle, Prepare: Only used internally.
    • Poll: Retrieves new I/O events; node will block here when appropriate.
    • Check: setImmediate() callbacks are invoked here.
    • Close Callbacks: Executes callbacks like socket.on('close', ...).

    Each phase has a FIFO queue of callbacks to execute. The Event Loop enters a given phase, performs any operations specific to that phase, then executes callbacks in that phase's queue until the queue is exhausted or the maximum number of callbacks has executed[1][2][3][4][5][6].

  2. Execution Order:

    • The Event Loop executes tasks from the event queue only when the call stack is empty, meaning there are no ongoing tasks.
    • It allows Node.js to perform non-blocking I/O operations by offloading operations to the system kernel, which can handle multiple operations executing in the background[2].
  3. Role of process.nextTick() and Microtasks:

    • process.nextTick() all...
middle

middle

Gợi ý câu hỏi phỏng vấn

middle

What is the difference between browser global scope and Node.js global scope?

middle

What is the relationship between Node.js and V8?

senior

Why to use Buffer instead of binary string to handle binary data ?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào