ماژول Domain در Node.js: مدیریت خطاها و رویدادها

ماژول node:domain در Node.js ابزاری برای مدیریت خطاها در عملیات‌های ورودی/خروجی (IO) و گروه‌بندی آن‌هاست. این ماژول به توسعه‌دهندگان اجازه می‌دهد خطاهای رخ‌داده در EventEmitterها یا Callbackها را به‌جای خروج ناگهانی برنامه، در یک دامنهٔ مشخص مدیریت کنند. با وجود این، ماژول Domain منسوخ شده و استفاده از آن توصیه نمی‌شود؛ در آینده باید به راهکارهای جایگزین مهاجرت کرد.

Domain classerror handlingimplicit bindingexplicit bindingcluster integration

~2 دقیقه مطالعه · آخرین به‌روزرسانی ۶ دی ۱۴۰۴

1. Introduction


The Domain module allows grouping I/O operations so that errors are caught by the active domain instead of terminating the process. This helps manage errors in complex applications but comes with risks and is deprecated.


2. Important Warning


Domain error handlers are not a substitute for safely shutting down a process. Improper use can lead to resource leaks and undefined states. The recommended approach is to gracefully handle requests and stop accepting new ones when errors occur.


3. Bad Example


// XXX WARNING! BAD IDEA!
const d = require('node:domain').create();
d.on('error', (er) => {
  console.log(`error, but oh well ${er.message}`);
});
d.run(() => {
  require('node:http').createServer((req, res) => {
    handleRequest(req, res);
  }).listen(PORT);
});

4. Better Example with Cluster


Combining Domain with the Cluster module allows safer error handling:


const cluster = require('node:cluster');
if (cluster.isPrimary) {
  cluster.fork();
  cluster.fork();
  cluster.on('disconnect', (worker) => {
    cluster.fork();
  });
} else {
  const domain = require('node:domain');
  const server = require('node:http').createServer((req, res) => {
    const d = domain.create();
    d.on('error', (er) => {
      res.statusCode = 500;
      res.end('Oops, there was a problem!\n');
      cluster.worker.disconnect();
    });
    d.add(req);
    d.add(res);
    d.run(() => {
      handleRequest(req, res);
    });
  });
}

5. Domain Features


  • domain.create(): Creates a new domain.
  • domain.add(emitter): Adds an EventEmitter or Timer to the domain.
  • domain.bind(callback): Binds a callback to the domain.
  • domain.intercept(callback): Similar to bind but intercepts error arguments.
  • domain.run(fn): Runs a function in the domain context.
  • domain.enter() and domain.exit(): Manage entering and exiting a domain.
  • domain.remove(emitter): Removes an EventEmitter or Timer from the domain.

6. Binding


Implicit binding: New EventEmitters are automatically bound to the active domain.
Explicit binding: EventEmitters or requests can be manually bound to a specific domain.


7. Domains and Promises


Since Node.js v8.0.0, Promise handlers run inside the domain where .then() or .catch() was called. Domains do not interfere with unhandled Promise rejection handling.


Conclusion


The Domain module provides error management for grouped I/O operations but is deprecated due to inherent risks. Developers should migrate to alternatives like async_hooks or structured error handling to ensure safer and more reliable applications.


نوشته و پژوهش‌شده توسط دکتر شاهین صیامی

مقالات مرتبط

آشنایی کامل با ماژول Cluster در Node.js و نحوه افزایش مقیاس‌پذیری سرور

ماژول Cluster در Node.js به توسعه‌دهندگان اجازه می‌دهد چندین پردازش همزمان ایجاد کنند که یک پورت سرور را به اشتراک می‌گذارند. این کار باعث استفاده بهتر از هسته‌های CPU و افزایش توان پردازش برنامه می‌شود. در این مقاله نحوه کار Cluster، مدیریت Workerها، تنظیمات مهم و مثال عملی را بررسی می‌کنیم.

ادامه

راهنمای جامع ماژول VM در Node.js (ماژول node:vm)

ماژول node:vm امکان کامپایل و اجرای کد جاوااسکریپت در کانتکست‌های ایزولهٔ V8 را فراهم می‌کند. این کانتکست‌ها مانند یک «سندباکس سبک» داخل برنامهٔ Node.js عمل می‌کنند و هرکدام globalThis مخصوص خود را دارند. این ماژول برای اجرای پویا، موتورهای قالب (Template Engines)، سیستم‌های افزونه (Plugin Systems)، REPLها و تست ایزولهٔ منطق بسیار مناسب است. اما نکتهٔ بسیار مهم: vm یک ابزار امنیتی نیست و نباید برای اجرای کدهای غیرقابل‌اعتماد استفاده شود.

ادامه

راهنمای جامع ماژول V8 در Node.js (ماژول node:v8)

راهنمای جامع ماژول V8 در Node.js (ماژول node:v8)

ادامه

راهنمای جامع Worker Threads در Node.js (ماژول node:worker_threads)

ماژول node:worker_threads امکان اجرای واقعی چندریسمانی (Multithreading) را در Node.js فراهم می‌کند. برخلاف مدل تک‌ریسمانی سنتی Node.js، Worker Threads اجازه می‌دهند کارهای سنگین CPU در ریسه‌های جداگانه اجرا شوند بدون اینکه حلقهٔ رویداد (Event Loop) مسدود شود. این ماژول از حافظهٔ اشتراکی، انتقال بدون کپی (Zero‑Copy)، کانال‌های پیام، Worker Pool، محدودیت منابع و ابزارهای همگام‌سازی پیشرفته پشتیبانی می‌کند. Worker Threads برای پردازش‌های محاسباتی سنگین ایده‌آل هستند، در حالی که I/O همچنان باید توسط ریسهٔ اصلی مدیریت شود.

ادامه

راهنمای جامع ماژول util در Node.js

ماژول node:util مجموعه‌ای از توابع کمکی قدرتمند برای استفاده در هستهٔ Node.js و همچنین توسعهٔ برنامه‌ها ارائه می‌دهد. این ماژول ابزارهایی برای دیباگ، بازرسی اشیا، تبدیل Callback ↔ Promise، قالب‌بندی رشته‌ها، بررسی انواع، مدیریت خطاها، رمزگذاری متن، پردازش MIME، پارس آرگومان‌های CLI، سیگنال‌های Abort، و ابزارهای متفرقه فراهم می‌کند. این ماژول یکی از جعبه‌ابزارهای اصلی و ضروری برای توسعه‌دهندگان Node.js است.

ادامه

راهنمای جامع ماژول URL در Node.js

ماژول node:url ابزارهایی برای تحلیل، ساخت، و دست‌کاری URLها در Node.js فراهم می‌کند. Node.js دو API برای کار با URL دارد: WHATWG URL API — استاندارد مدرن و سازگار با مرورگرها (توصیه‌شده). Legacy API — API قدیمی Node.js (غیرتوصیه‌شده). WHATWG URL API یک رابط تمیز، سازگار و قدرتمند برای کار با اجزای URL، پارامترهای query، الگوهای URL و حتی Blob URLها ارائه می‌دهد.

ادامه