domain.run(fn[, ...args])
fn
<Function>...args
<any>
在域的上下文中运行提供的函数,隐式地绑定在该上下文中创建的所有事件触发器、定时器和低层请求。 可选地,参数可以传给函数。
这是使用域的最基本方式。
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(() => { // 模拟各种异步的东西
fs.open('non-existent file', 'r', (er, fd) => {
if (er) throw er;
// 继续...
});
}, 100);
});
});
在本例中,将触发 d.on('error')
句柄,而不是使程序崩溃。
fn
<Function>...args
<any>
Run the supplied function in the context of the domain, implicitly binding all event emitters, timers, and lowlevel 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);
});
});
In this example, the d.on('error')
handler will be triggered, rather
than crashing the program.