domain.run(fn[, ...args])
fn<Function>...args<any>
在该域的上下文中运行提供的函数,隐式绑定在该上下文中创建的所有事件触发器、计时器和低级请求。可以选择向函数传递参数。
【Run the supplied function in the context of the domain, implicitly binding all event emitters, timers, and low-level requests that are created in that context. Optionally, arguments can be passed to the function.】
这是使用域的最基本方式。
【This is the most basic way to use a domain.】
const domain = require('node:domain');
const fs = require('node:fs');
const d = domain.create();
d.on('error', (er) => {
console.error('Caught error!', er);
});
d.run(() => {
process.nextTick(() => {
setTimeout(() => { // Simulating some various async stuff
fs.open('non-existent file', 'r', (er, fd) => {
if (er) throw er;
// proceed...
});
}, 100);
});
}); 在这个例子中,d.on('error') 处理程序会被触发,而不会导致程序崩溃。
【In this example, the d.on('error') handler will be triggered, rather
than crashing the program.】