~3 دقیقه مطالعه • بروزرسانی ۶ دی ۱۴۰۴
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()anddomain.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.
نوشته و پژوهش شده توسط دکتر شاهین صیامی