0Pricing
Node.js Backend Development Bootcamp · درس

تحسين حلقة الأحداث في Node.js

تعمّقوا في حلقة الأحداث لتحديد العمليات الحاجبة وتحسين التعليمات البرمجية غير المتزامنة لتحقيق أداء أفضل

تحسين حلقة الأحداث في Node.js درس مجاني في Node.js Backend Development Bootcamp على CoddyKit. هذا هو الدرس 3 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في Node.js Backend Development Bootcamp، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة Node.js Backend Development Bootcamp 4 دروس في المجموع.

بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.

Event Loop: The Heart of Node.js

Welcome! Node.js uses a single-threaded model, but it handles many operations concurrently thanks to its Event Loop. This loop continuously checks for tasks to execute.

Optimizing the event loop is crucial for high-performance Node.js applications. It ensures your server remains responsive and handles many users efficiently.

تحسين حلقة الأحداث في Node.js — رسم توضيحي 1

Understanding Blocking Operations

A blocking operation (or synchronous operation) is one that halts the execution of all other JavaScript code until it completes. Imagine a single cashier stopping to count change for one customer while a long line of other customers waits.

In Node.js, a blocking operation freezes the entire event loop, preventing it from processing other incoming requests or tasks. This leads to slow response times and a poor user experience.

Spotting CPU-Hogging Code

CPU-bound tasks are operations that consume a lot of processor time. They don't wait for external resources like databases or network requests; they just crunch numbers.

  • Complex calculations
  • Heavy data transformations
  • Synchronous loops over very large datasets
  • Image processing or cryptography

These are common culprits for blocking the event loop if not handled carefully.

Demo: A Blocking Loop

Try running this example. Notice how the 'After blocking loop' message is delayed, and if this were a server, it wouldn't respond to other requests during the loop's execution.

console.log("Before blocking loop.");

const startTime = Date.now();
// Simulate a CPU-intensive task
for (let i = 0; i < 5000000000; i++) {
  // Do nothing, just loop
}
const endTime = Date.now();

console.log(`Blocking loop finished in ${endTime - startTime}ms.`);
console.log("After blocking loop.");

// This will be delayed because the loop blocked the event loop
setTimeout(() => {
  console.log("This message is from setTimeout (delayed).");
}, 0);

Breaking Down CPU-Bound Work

To prevent blocking, we can break large CPU-bound tasks into smaller chunks and defer their execution. This allows the event loop to process other tasks between chunks.

  • Use setImmediate() to schedule a function to run after the current poll phase of the event loop.
  • Use process.nextTick() to schedule a function to run before any I/O operations in the current event loop phase.
  • For truly heavy computations, use Worker Threads.

Demo: Deferring with setImmediate

Here, we refactor the blocking loop using setImmediate. This allows the event loop to process the setTimeout callback much sooner, even though the total work is still performed.

console.log("Before deferred loop.");

let count = 0;
const maxCount = 5000000000;

function doWorkChunk() {
  const chunkSize = 10000000; // Process 10 million iterations at a time
  const start = count;
  const end = Math.min(count + chunkSize, maxCount);

  for (let i = start; i < end; i++) {
    // Simulate work
  }

  count = end;

  if (count < maxCount) {
    setImmediate(doWorkChunk); // Schedule next chunk immediately
  } else {
    console.log("Deferred loop finished.");
  }
}

const startTime = Date.now();
setImmediate(doWorkChunk); // Start the deferred work

console.log("After initiating deferred loop.");

// This setTimeout will run much sooner now
setTimeout(() => {
  console.log("This message is from setTimeout (not delayed).");
  const endTime = Date.now();
  console.log(`Total time (approx) for deferred loop: ${endTime - startTime}ms.`);
}, 0);

process.nextTick vs. setImmediate

Both process.nextTick() and setImmediate() defer execution, but they operate in different phases of the event loop:

  • process.nextTick(): Runs its callback *before* any I/O callbacks in the *current* event loop turn. It's often used for error handling or normalizing callback behavior.
  • setImmediate(): Runs its callback in the *check* phase, *after* I/O callbacks and before timers in the *next* event loop turn. It's ideal for breaking up long-running tasks.

Beyond Main Thread: Worker Threads

For truly CPU-intensive operations that cannot be easily broken into small chunks, Node.js offers Worker Threads. These allow you to run JavaScript code in parallel, in completely separate threads.

Worker Threads do not block the main event loop at all, making them perfect for heavy computations like data encryption, complex simulations, or large file processing.

Demo: Basic Worker Thread

Here's how a main.js file can use a worker to offload heavy computation. The main thread remains free to do other work.

You would also need a worker.js file in the same directory:

const { parentPort } = require('worker_threads'); parentPort.on('message', (task) => { console.log('Worker received task:', task); let result = 0; for (let i = 0; i < task; i++) { result += i; // Simulate heavy computation } parentPort.postMessage(result); });
const { Worker } = require('worker_threads');

console.log("Main thread started.");

// Create a new worker thread (requires 'worker.js' file)
const worker = new Worker('./worker.js');

// Listen for messages from the worker
worker.on('message', (msg) => {
  console.log(`Worker finished: Result = ${msg}`);
});

// Listen for errors from the worker
worker.on('error', (err) => {
  console.error(`Worker error: ${err}`);
});

// Listen for worker exit
worker.on('exit', (code) => {
  if (code !== 0)
    console.error(`Worker stopped with exit code ${code}`);
});

// Send a heavy task to the worker
worker.postMessage(500000000); // Send a large number for heavy computation

console.log("Main thread sent task to worker.");
console.log("Main thread continues non-blocking work.");

// Simulate other work in the main thread
let mainThreadCounter = 0;
const intervalId = setInterval(() => {
  console.log(`Main thread doing other work: ${mainThreadCounter++}`);
  if (mainThreadCounter >= 5) {
    clearInterval(intervalId);
  }
}, 100);

Check Your Understanding

Consider a Node.js web server. Which of the following operations is MOST likely to block the event loop and negatively impact server responsiveness?

Recap: Optimizing the Event Loop

Great job! You've learned how to keep the Node.js event loop running smoothly for optimal performance:

  • Identify Blocking Code: Recognize synchronous, CPU-intensive tasks.
  • Break Up Work: Use setImmediate() or process.nextTick() to defer parts of long tasks.
  • Leverage Worker Threads: Offload heavy computations to separate threads for true parallelism.

By preventing the event loop from blocking, your Node.js applications will remain responsive and efficient, even under heavy load.

الأسئلة الشائعة

هل درس «تحسين حلقة الأحداث في Node.js» مجاني؟

نعم — نص درس «تحسين حلقة الأحداث في Node.js» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة Node.js Backend Development Bootcamp، انتقل إلى CoddyKit PRO. تتضمن دورة Node.js Backend Development Bootcamp 4 دروس في المجموع.

ماذا ستتعلم في «تحسين حلقة الأحداث في Node.js»؟

تعمّقوا في حلقة الأحداث لتحديد العمليات الحاجبة وتحسين التعليمات البرمجية غير المتزامنة لتحقيق أداء أفضل تتمرن على Node.js Backend Development Bootcamp مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.

هل أحتاج إلى خبرة سابقة لأبدأ Node.js Backend Development Bootcamp؟

لا تُشترط خبرة سابقة. Node.js Backend Development Bootcamp على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 3 من أصل 4.

كم من الوقت يستغرق درس «تحسين حلقة الأحداث في Node.js»؟

معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.

هل يمكنني كتابة وتشغيل أكواد في درس Node.js Backend Development Bootcamp هذا؟

نعم. كل درس في Node.js Backend Development Bootcamp يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.

جميع الدروس في هذه الدورة

  1. استراتيجيات التخزين المؤقت لـ Node.js
  2. موازنة التحميل لتطبيقات Node.js
  3. تحسين حلقة الأحداث في Node.js
  4. تحليل الأداء واكتشاف تسرّب الذاكرة
← العودة إلى Node.js Backend Development Bootcamp