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.