Topics Node.js Fundamentals Event Loop & Global Objects
intermediate 18 min read

Event Loop & Global Objects

How the event loop works, microtasks vs macrotasks, and Node.js global objects.

The Event Loop

The event loop is what allows Node.js to perform non-blocking I/O operations despite being single-threaded.

console.log("1: Start");\n\nsetTimeout(() => console.log("2: Timeout"), 0);\n\nPromise.resolve().then(() => console.log("3: Promise"));\n\nprocess.nextTick(() => console.log("4: nextTick"));\n\nconsole.log("5: End");\n\n// Output: 1, 5, 4, 3, 2

Event Loop Phases

  1. timers: executes setTimeout/setInterval callbacks
  2. pending callbacks: I/O callbacks deferred to next iteration
  3. idle, prepare: internal use
  4. poll: retrieve new I/O events
  5. check: setImmediate callbacks
  6. close callbacks: close event callbacks

Global Objects

// In Node.js, these are global:\nglobalThis;  // The global object (like window in browsers)\nconsole;     // Console for logging\nprocess;     // Current Node.js process\nBuffer;      // Handle binary data\n__dirname;   // Current directory path\n__filename;  // Current file path\nsetTimeout;  // Schedule a one-time callback\nsetInterval; // Schedule a repeating callback\nsetImmediate;// Schedule callback for check phase

Examples

// Demonstrating event loop phases
const fs = require('fs');

// Timer phase
setTimeout(() => console.log('1: Timer'), 0);

// Check phase
setImmediate(() => console.log('2: setImmediate'));

// Poll phase - I/O callback
fs.readFile(__filename, () => {
  console.log('3: I/O callback');
  
  setTimeout(() => console.log('4: Timer inside I/O'), 0);
  setImmediate(() => console.log('5: setImmediate inside I/O'));
  process.nextTick(() => console.log('6: nextTick inside I/O'));
});

console.log('7: Synchronous');

Your Notes

Sign in to take notes for this lesson.

Quiz

Node.js Fundamentals Quiz

0 questions

Sign in to take quiz

Discussion

Sign in to join the discussion.

Flashcards

Sign in to create flashcards.