Node.js v26.0.0 文档
- Node.js v26.0.0
- 目录
- 索引
- 关于本文档
- 用法与示例
- 断言测试
- 异步上下文跟踪
- 异步钩子
- 缓冲区
- C++ 插件
- 使用 Node-API 的 C/C++ 插件
- C++ 嵌入器 API
- 子进程
- 集群
- 命令行选项
- 控制台
- 加密
- 调试器
- 已弃用的 API
- 诊断通道
- DNS
- 域
- 环境变量
- 错误
- 事件
- 文件系统
- 全局对象
- HTTP
- HTTP/2
- HTTPS
- 检查器
- 国际化
- 模块:CommonJS 模块
- 模块:ECMAScript 模块
- 模块:
node:moduleAPI - 模块:包
- 模块:TypeScript
- 网络
- 可迭代流 API
- 操作系统
- 路径
- 性能钩子
- 权限
- 进程
- Punycode
- 查询字符串
- 逐行读取
- REPL
- 报告
- 单一可执行文件应用
- SQLite
- 流
- 字符串解码器
- 测试运行器
- 定时器
- TLS/SSL
- 跟踪事件
- TTY
- UDP/数据报
- URL
- 实用工具
- V8
- 虚拟机
- WASI
- Web Crypto API
- Web Streams API
- 工作线程
- Zlib
- Zlib 可迭代压缩
- 其他版本
- 选项
Domain(域)#
稳定性: 0 - 废弃
该模块即将被废弃。一旦最终确定了替代 API,该模块将被完全废弃。大多数开发者不应有理由使用此模块。那些必须使用域所提供功能的开发者可以暂时依赖它,但应预期未来需要迁移到其他解决方案。
域提供了一种将多个不同的 IO 操作作为单个组进行处理的方法。如果注册到域的任何事件触发器或回调触发了 'error' 事件或抛出了错误,则域对象会收到通知,而不是在 process.on('uncaughtException') 处理程序中丢失错误的上下文,或者导致程序因错误代码而立即退出。
警告:不要忽略错误!#
域错误处理程序不能替代发生错误时关闭进程的做法。
根据 JavaScript 中 throw 的本质工作方式,在不泄漏引用或产生其他未定义的脆弱状态的情况下,几乎没有任何方法可以安全地“从中断处继续”。
响应抛出错误的最安全方法是关闭进程。当然,在普通的 Web 服务器中,可能存在许多打开的连接,仅仅因为某人的错误触发而突然关闭这些连接是不合理的。
更好的方法是向触发错误的请求发送错误响应,同时让其他请求在正常时间内完成,并停止在该工作进程中监听新请求。
通过这种方式,domain 的使用与 cluster 模块相辅相成,因为当工作进程遇到错误时,主进程可以派生一个新的工作进程。对于扩展到多台机器的 Node.js 程序,终止代理或服务注册中心可以记录该故障,并做出相应反应。
例如,这并不是一个好主意
// XXX WARNING! BAD IDEA!
const d = require('node:domain').create();
d.on('error', (er) => {
// The error won't crash the process, but what it does is worse!
// Though we've prevented abrupt process restarting, we are leaking
// a lot of resources if this ever happens.
// This is no better than process.on('uncaughtException')!
console.log(`error, but oh well ${er.message}`);
});
d.run(() => {
require('node:http').createServer((req, res) => {
handleRequest(req, res);
}).listen(PORT);
});
通过使用域的上下文,以及将程序分离为多个工作进程的弹性,我们可以做出更适当的反应,并以更高的安全性处理错误。
// Much better!
const cluster = require('node:cluster');
const PORT = +process.env.PORT || 1337;
if (cluster.isPrimary) {
// A more realistic scenario would have more than 2 workers,
// and perhaps not put the primary and worker in the same file.
//
// It is also possible to get a bit fancier about logging, and
// implement whatever custom logic is needed to prevent DoS
// attacks and other bad behavior.
//
// See the options in the cluster documentation.
//
// The important thing is that the primary does very little,
// increasing our resilience to unexpected errors.
cluster.fork();
cluster.fork();
cluster.on('disconnect', (worker) => {
console.error('disconnect!');
cluster.fork();
});
} else {
// the worker
//
// This is where we put our bugs!
const domain = require('node:domain');
// See the cluster documentation for more details about using
// worker processes to serve requests. How it works, caveats, etc.
const server = require('node:http').createServer((req, res) => {
const d = domain.create();
d.on('error', (er) => {
console.error(`error ${er.stack}`);
// We're in dangerous territory!
// By definition, something unexpected occurred,
// which we probably didn't want.
// Anything can happen now! Be very careful!
try {
// Make sure we close down within 30 seconds
const killtimer = setTimeout(() => {
process.exit(1);
}, 30000);
// But don't keep the process open just for that!
killtimer.unref();
// Stop taking new requests.
server.close();
// Let the primary know we're dead. This will trigger a
// 'disconnect' in the cluster primary, and then it will fork
// a new worker.
cluster.worker.disconnect();
// Try to send an error to the request that triggered the problem
res.statusCode = 500;
res.setHeader('content-type', 'text/plain');
res.end('Oops, there was a problem!\n');
} catch (er2) {
// Oh well, not much we can do at this point.
console.error(`Error sending 500! ${er2.stack}`);
}
});
// Because req and res were created before this domain existed,
// we need to explicitly add them.
// See the explanation of implicit vs explicit binding below.
d.add(req);
d.add(res);
// Now run the handler function in the domain.
d.run(() => {
handleRequest(req, res);
});
});
server.listen(PORT);
}
// This part is not important. Just an example routing thing.
// Put fancy application logic here.
function handleRequest(req, res) {
switch (req.url) {
case '/error':
// We do some async stuff, and then...
setTimeout(() => {
// Whoops!
flerb.bark();
}, timeout);
break;
default:
res.end('ok');
}
}
Error 对象的补充#
每当 Error 对象通过域路由时,都会向其添加一些额外字段。
error.domain最初处理该错误的域。error.domainEmitter触发带有错误对象的'error'事件的事件触发器。error.domainBound绑定到该域且第一个参数被传递了错误的回调函数。error.domainThrown一个布尔值,指示错误是抛出的、触发的,还是传递给绑定回调函数的。
隐式绑定#
如果正在使用域,则所有新的 EventEmitter 对象(包括流对象、请求、响应等)在创建时都会隐式绑定到活动域。
此外,传递给底层事件循环请求(例如 fs.open() 或其他接受回调的方法)的回调将自动绑定到活动域。如果它们抛出错误,则该域将捕获该错误。
为了防止过度的内存使用,Domain 对象本身不会隐式添加为活动域的子级。如果这样做,那么请求和响应对象将很容易无法被正确地垃圾回收。
要将 Domain 对象嵌套为父级 Domain 的子级,它们必须被显式添加。
隐式绑定将抛出的错误和 'error' 事件路由到 Domain 的 'error' 事件,但不会在 Domain 上注册该 EventEmitter。隐式绑定仅处理抛出的错误和 'error' 事件。
显式绑定#
有时,正在使用的域并不是特定事件触发器应该使用的域。或者,事件触发器可能是在一个域的上下文中创建的,但却应该绑定到另一个域。
例如,HTTP 服务器可能正在使用一个域,但我们可能希望为每个请求使用单独的域。
这可以通过显式绑定来实现。
// Create a top-level domain for the server
const domain = require('node:domain');
const http = require('node:http');
const serverDomain = domain.create();
serverDomain.run(() => {
// Server is created in the scope of serverDomain
http.createServer((req, res) => {
// Req and res are also created in the scope of serverDomain
// however, we'd prefer to have a separate domain for each request.
// create it first thing, and add req and res to it.
const reqd = domain.create();
reqd.add(req);
reqd.add(res);
reqd.on('error', (er) => {
console.error('Error', er, req.url);
try {
res.writeHead(500);
res.end('Error occurred, sorry.');
} catch (er2) {
console.error('Error sending 500', er2, req.url);
}
});
}).listen(1337);
});
domain.create()#
- 返回:
<Domain>
类:Domain#
- 扩展自:
<EventEmitter>
Domain 类封装了将错误和未捕获异常路由到活动 Domain 对象的功能。
要处理它捕获的错误,请监听其 'error' 事件。
domain.members#
- 类型:
<Array>
已显式添加到该域的事件触发器数组。
domain.add(emitter)#
emitter<EventEmitter>要添加到域中的触发器
将触发器显式添加到域中。如果触发器调用的任何事件处理程序抛出错误,或者触发器触发了 'error' 事件,它将被路由到该域的 'error' 事件,就像隐式绑定一样。
如果 EventEmitter 已经绑定到某个域,它将从该域中移除,并改为绑定到当前域。
domain.bind(callback)#
callback<Function>回调函数- 返回:
<Function>绑定后的函数
返回的函数将是所提供回调函数的包装器。当调用返回的函数时,任何抛出的错误都将路由到该域的 'error' 事件。
const d = domain.create();
function readSomeFile(filename, cb) {
fs.readFile(filename, 'utf8', d.bind((er, data) => {
// If this throws, it will also be passed to the domain.
return cb(er, data ? JSON.parse(data) : null);
}));
}
d.on('error', (er) => {
// An error occurred somewhere. If we throw it now, it will crash the program
// with the normal line number and stack message.
});
domain.enter()#
enter() 方法是 run()、bind() 和 intercept() 方法使用的底层管道,用于设置活动域。它将 domain.active 和 process.domain 设置为该域,并隐式地将域推入由 domain 模块管理的域栈(有关域栈的详细信息,请参阅 domain.exit())。对 enter() 的调用界定了绑定到域的一系列异步调用和 I/O 操作链的开始。
调用 enter() 仅更改活动域,而不改变域本身。可以在单个域上多次调用 enter() 和 exit()。
domain.exit()#
exit() 方法退出当前域,将其从域栈中弹出。每当执行即将切换到不同异步调用链的上下文时,确保当前域已退出非常重要。对 exit() 的调用界定了绑定到域的一系列异步调用和 I/O 操作链的结束或中断。
如果当前执行上下文中绑定了多个嵌套域,exit() 将退出该域内的任何嵌套域。
调用 exit() 仅更改活动域,而不改变域本身。可以在单个域上多次调用 enter() 和 exit()。
domain.intercept(callback)#
callback<Function>回调函数- 返回:
<Function>被拦截后的函数
此方法几乎与 domain.bind(callback) 相同。但是,除了捕获抛出的错误外,它还会拦截作为函数第一个参数发送的 Error 对象。
通过这种方式,通用的 if (err) return callback(err); 模式可以被单一位置的单一错误处理程序所取代。
const d = domain.create();
function readSomeFile(filename, cb) {
fs.readFile(filename, 'utf8', d.intercept((data) => {
// Note, the first argument is never passed to the
// callback since it is assumed to be the 'Error' argument
// and thus intercepted by the domain.
// If this throws, it will also be passed to the domain
// so the error-handling logic can be moved to the 'error'
// event on the domain instead of being repeated throughout
// the program.
return cb(null, JSON.parse(data));
}));
}
d.on('error', (er) => {
// An error occurred somewhere. If we throw it now, it will crash the program
// with the normal line number and stack message.
});
domain.remove(emitter)#
emitter<EventEmitter>要从域中移除的触发器
domain.add(emitter) 的反向操作。从指定的触发器中移除域处理。
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(() => { // Simulating some various async stuff
fs.open('non-existent file', 'r', (er, fd) => {
if (er) throw er;
// proceed...
});
}, 100);
});
});
在此示例中,将触发 d.on('error') 处理程序,而不是导致程序崩溃。
域与 Promise#
从 Node.js 8.0.0 开始,promise 的处理程序运行在调用 .then() 或 .catch() 本身的那个域内。
const d1 = domain.create();
const d2 = domain.create();
let p;
d1.run(() => {
p = Promise.resolve(42);
});
d2.run(() => {
p.then((v) => {
// running in d2
});
});
可以使用 domain.bind(callback) 将回调绑定到特定域。
const d1 = domain.create();
const d2 = domain.create();
let p;
d1.run(() => {
p = Promise.resolve(42);
});
d2.run(() => {
p.then(p.domain.bind((v) => {
// running in d1
}));
});
域不会干扰 promise 的错误处理机制。换句话说,不会为未处理的 Promise 拒绝触发 'error' 事件。