Optionaloptions: MongoClientOptionsReadonlyoptionsThe consolidate, parsed, transformed and merged options.整合、解析、转换和合并选项。
StaticcaptureValue: boolean
Change the default 更改所有新captureRejections option on all new EventEmitter objects.EventEmitter对象的默认captureRejections选项。
Static ReadonlycaptureValue: Symbol.for('nodejs.rejection')
See how to write a custom 了解如何编写自定义拒绝处理程序。rejection handler.
StaticdefaultBy default, a maximum of 默认情况下,任何单个事件最多可以注册10 listeners can be registered for any single event. 10个侦听器。This limit can be changed for individual 可以使用EventEmitter instances using the emitter.setMaxListeners(n) method. emitter.setMaxListeners(n)方法更改单个EventEmitter实例的此限制。To change the default for all要更改所有EventEmitter instances, the events.defaultMaxListeners property can be used. EventEmitter实例的默认值,可以使用events.defaultMaxListeners属性。If this value is not a positive number, a 如果此值不是正数,则抛出RangeError is thrown.RangeError。
Take caution when setting the 设置events.defaultMaxListeners because the change affects all EventEmitter instances, including those created before the change is made. events.defaultMaxListeners时要小心,因为更改会影响所有EventEmitter实例,包括在更改之前创建的实例。However, calling 但是,调用emitter.setMaxListeners(n) still has precedence over events.defaultMaxListeners.emitter.setMaxListeners(n)仍然优先于events.defaultMaxListeners。
This is not a hard limit. The 这不是一个硬性限制。EventEmitter instance will allow more listeners to be added but will output a trace warning to stderr indicating that a "possible EventEmitter memory leak" has been detected. EventEmitter实例将允许添加更多侦听器,但会向stderr输出跟踪警告,指示已检测到“可能的EventEmitters内存泄漏”。For any single 对于任何单个EventEmitter, the emitter.getMaxListeners() and emitter.getMaxListeners() methods can be used to temporarily avoid this warning:EventEmitter,可以使用emitter.getMaxListeners()和emitter.getMaxListeners()方法暂时避免此警告:
import { EventEmitter } from 'node:events';
const emitter = new EventEmitter();
emitter.setMaxListeners(emitter.getMaxListeners() + 1);
emitter.once('event', () => {
// do stuff做事
emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0));
});
The --trace-warnings command-line flag can be used to display the stack trace for such warnings.--trace-warnings命令行标志可用于显示此类警告的堆栈跟踪。
The emitted warning can be inspected with 可以使用process.on('warning') and will have the additional emitter, type, and count properties, referring to the event emitter instance, the event's name and the number of attached listeners, respectively. process.on('warning')检查发出的警告,并将具有额外的emitter、type和count属性,分别引用事件发射器实例、事件名称和附加侦听器的数量。Its 其name property is set to 'MaxListenersExceededWarning'.name属性设置为'MaxListenersExceededWarning'。
Static ReadonlyerrorThis symbol shall be used to install a listener for only monitoring 此符号应用于安装仅用于监视'error' events. Listeners installed using this symbol are called before the regular 'error' listeners are called.'error'事件的侦听器。使用此符号安装的侦听器在调用常规'error'侦听器之前被调用。
Installing a listener using this symbol does not change the behavior once an 一旦发出'error' event is emitted. Therefore, the process will still crash if no regular 'error' listener is installed.'error'事件,使用此符号安装侦听器不会改变行为。因此,如果没有安装常规的'error'侦听器,该进程仍将崩溃。
Experimental
An alias for MongoClient.close().
Optional[captureRest...args: AnyRestAlias for emitter.on(eventName, listener).
Alias for emitter.on(eventName, listener).
Alias for emitter.on(eventName, listener).
Append metadata to the client metadata after instantiation.实例化后将元数据附加到客户端元数据。
Information about the application or library.有关应用程序或库的信息。
Executes a client bulk write operation, available on server 8.0+.执行客户端批量写入操作,可在服务器8.0+上使用。
The client bulk write models.客户端批量写入模型。
Optionaloptions: ClientBulkWriteOptions
The client bulk write options.客户端批量写入选项。
A ClientBulkWriteResult for acknowledged writes and ok: 1 for unacknowledged writes.ClientBulkWriteResult表示已确认的写入,ok:1表示未确认的写入。
Cleans up resources managed by the MongoClient.清理MongoClient管理的资源。
The close method clears and closes all resources whose lifetimes are managed by the MongoClient. Please refer to the close方法清除并关闭其生命周期由MongoClient管理的所有资源。请参阅MongoClient class documentation for a high level overview of the client's key features and responsibilities.MongoClient类文档,了解客户端关键功能和职责的高级概述。
However, the close method does not handle the cleanup of resources explicitly created by the user. Any user-created driver resource with its own 但是,close方法不处理用户显式创建的资源的清理。任何用户创建的具有自己的close() method should be explicitly closed by the user before calling MongoClient.close(). This method is written as a "best effort" attempt to leave behind the least amount of resources server-side when possible.close()方法的驱动程序资源都应该在调用MongoClient.close()之前由用户显式关闭。此方法被编写为“尽最大努力”的尝试,尽可能在服务器端留下最少的资源。
The following list defines ideal preconditions and consequent pitfalls if they are not met. The MongoClient, ClientSession, Cursors and ChangeStreams all support explicit resource management. 以下列表定义了理想的先决条件以及如果不满足这些先决条件则可能出现的陷阱。MongoClient、ClientSession、Cursors和ChangeStreams都支持显式资源管理。By using explicit resource management to manage the lifetime of driver resources instead of manually managing their lifetimes, the pitfalls outlined below can be avoided.通过使用显式资源管理来管理驱动程序资源的生命周期,而不是手动管理其生命周期,可以避免下面概述的陷阱。
The close method performs the following in the order listed:close方法按所列顺序执行以下操作:
client.close() is called and all connections are in use, after closing them, the client must create new connections for cleanup operations, which comes at the cost of new TLS/TCP handshakes and authentication steps.client.close()并且所有连接都在使用中时,在关闭它们之后,客户端必须创建新的连接进行清理操作,这是以新的TLS/TCP握手和身份验证步骤为代价的。killCursor operation sent to the server they were initialized on, freeing the server-side resource.killCursor操作,从而释放服务器端资源。
client.close() is called.client.close()之前显式关闭或完成。killCursors may have to build a new connection if the in-use closure ended all pooled connections.killCursor可能必须建立一个新的连接,如果正在使用的闭包结束了所有池连接。client.startSession() or client.withSession() or implicitly by the driver will have their .endSession() method called. client.startSession()或client.withSession()创建的或由驱动程序隐式创建的在用会话将调用其.endSession()方法。endSession() returns the session to the client's pool of sessions rather than end them on the server.endSession()将会话返回到客户端的会话池,而不是在服务器上结束它们。
client.close() is called.client.close()之前结束其相应的显式会话。endSessions command with all session IDs the client has pooled is sent to the server to inform the cluster it can clean them up.endSessions命令发送到服务器,通知集群可以清理它们。
The remaining shutdown is of the MongoClient resources that are intended to be entirely internal but is documented here as their existence relates to the JS event loop.剩下的关闭是MongoClient资源,这些资源本来是完全内部的,但在这里被记录下来,因为它们的存在与JS事件循环有关。
mongocryptd or other encryption purposes is closed. (Using this same method of course!)mongocryptd通信或其他加密目的而创建的内部MongoClient已关闭。(当然是用同样的方法!)After the close method completes there should be no MongoClient related resources ref-ed in Node.js' event loop. This should allow Node.js to exit gracefully if MongoClient resources were the only active handles in the event loop.close方法完成后,Node.js的事件循环中应该没有引用与MongoClient相关的资源。如果MongoClient资源是事件循环中唯一的活动句柄,这应该允许Node.js优雅地退出。
currently an unused flag that has no effect. Defaults to 当前为无效的未使用标志。默认为false.false。
An optional method to verify a handful of assumptions that are generally useful at application boot-time before using a MongoClient. For detailed information about the connect process see the MongoClient.connect static method documentation.一种可选方法,用于在使用MongoClient之前在应用程序启动时验证一些通常有用的假设。有关连接过程的详细信息,请参阅MongoClient.connect静态方法文档。
Create a new Db instance sharing the current socket connections.创建一个共享当前套接字连接的新Db实例。
OptionaldbName: string
The name of the database we want to use. If not provided, use database name from connection string.我们要使用的数据库的名称。如果没有提供,请使用连接字符串中的数据库名称。
Optionaloptions: DbOptions
Optional settings for Db constructionDb构造的可选设置
Synchronously calls each of the listeners registered for the event named 按照注册顺序同步调用为名为eventName, in the order they were registered, passing the supplied arguments to each.eventName的事件注册的每个侦听器,将提供的参数传递给每个侦听器。
Returns 如果事件有侦听器,则返回true if the event had listeners, false otherwise.true,否则返回false。
import { EventEmitter } from 'node:events';
const myEmitter = new EventEmitter();
// First listener第一个侦听器
myEmitter.on('event', function firstListener() {
console.log('Helloooo! first listener');
});
// Second listener第二个侦听器
myEmitter.on('event', function secondListener(arg1, arg2) {
console.log(`event with parameters ${arg1}, ${arg2} in second listener`);
});
// Third listener第三个侦听器
myEmitter.on('event', function thirdListener(...args) {
const parameters = args.join(', ');
console.log(`event with parameters ${parameters} in third listener`);
});
console.log(myEmitter.listeners('event'));
myEmitter.emit('event', 1, 2, 3, 4, 5);
// Prints:打印:
// [
// [Function: firstListener],
// [Function: secondListener],
// [Function: thirdListener]
// ]
// Helloooo! first listener event with parameters 1, 2 in second listener event with parameters 1, 2, 3, 4, 5 in third listener你好!在第三个监听器中具有参数1、2的第二个监听器事件中的参数为1、2、3、4、5的第一个监听器事件
Rest...args: Parameters<MongoClientEvents[EventKey]>Returns an array listing the events for which the emitter has registered listeners. The values in the array are strings or 返回一个数组,列出发射器已注册侦听器的事件。数组中的值是字符串或符号Symbols.Symbol。
import { EventEmitter } from 'node:events';
const myEE = new EventEmitter();
myEE.on('foo', () => {});
myEE.on('bar', () => {});
const sym = Symbol('symbol');
myEE.on(sym, () => {});
console.log(myEE.eventNames());
// Prints: [ 'foo', 'bar', Symbol(symbol) ]
Returns the current max listener value for the 返回EventEmitter which is either set by emitter.setMaxListeners(n) or defaults to EventEmitter.defaultMaxListeners.EventEmitter的当前最大侦听器值,该值由emitter.setMaxListeners(n)设置或默认为EventEmitter.defaultMaxListeners。
Returns the number of listeners listening for the event named 返回侦听名为eventName. If listener is provided, it will return how many times the listener is found in the list of the listeners of the event.eventName的事件的侦听器数量。如果提供了listener,它将返回在事件监听器列表中找到监听器的次数。
Returns a copy of the array of listeners for the event named 返回名为eventName.eventName的事件的侦听器数组的副本。
server.on('connection', (stream) => {
console.log('someone connected!');
});
console.log(util.inspect(server.listeners('connection')));
// Prints: [ [Function] ]
Alias for emitter.removeListener().emitter.removeListener()的别名。
Alias for emitter.removeListener().emitter.removeListener()的别名。
Alias for emitter.removeListener().emitter.removeListener()的别名。
Adds the 将listener function to the end of the listeners array for the event named eventName. No checks are made to see if the listener has already been added. Multiple calls passing the same combination of eventName and listener will result in the listener being added, and called, multiple times.listener函数添加到名为eventName的事件的侦听器数组末尾。不检查是否已添加侦听器。传递相同eventName和listener组合的多个调用将导致listener被多次添加和调用。
server.on('connection', (stream) => {
console.log('someone connected!');
});
Returns a reference to the 返回对EventEmitter, so that calls can be chained.EventEmitter的引用,以便可以链接调用。
By default, event listeners are invoked in the order they are added. The 默认情况下,事件侦听器按添加顺序调用。emitter.prependListener() method can be used as an alternative to add the event listener to the beginning of the listeners array.emitter.prependListener()方法可以用作将事件侦听器添加到侦听器数组开头的替代方法。
import { EventEmitter } from 'node:events';
const myEE = new EventEmitter();
myEE.on('foo', () => console.log('a'));
myEE.prependListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
The callback function回调函数
Adds the 将listener function to the end of the listeners array for the event named eventName. listener函数添加到名为eventName的事件的侦听器数组末尾。No checks are made to see if the 不检查是否已添加listener has already been added. Multiple calls passing the same combination of eventName and listener will result in the listener being added, and called, multiple times.listener。传递相同eventName和listener组合的多个调用将导致listener被多次添加和调用。
server.on('connection', (stream) => {
console.log('someone connected!');
});
Returns a reference to the 返回对EventEmitter, so that calls can be chained.EventEmitter的引用,以便可以链接调用。
By default, event listeners are invoked in the order they are added. The 默认情况下,事件侦听器按添加顺序调用。emitter.prependListener() method can be used as an alternative to add the event listener to the beginning of the listeners array.emitter.prependListener()方法可以用作将事件侦听器添加到侦听器数组开头的替代方法。
import { EventEmitter } from 'node:events';
const myEE = new EventEmitter();
myEE.on('foo', () => console.log('a'));
myEE.prependListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
The callback function
Adds the 将listener function to the end of the listeners array for the event named eventName. listener函数添加到名为eventName的事件的侦听器数组末尾。No checks are made to see if the 不检查是否已添加listener has already been added. Multiple calls passing the same combination of eventName and listener will result in the listener being added, and called, multiple times.listener。传递相同eventName和listener组合的多个调用将导致侦听器被多次添加和调用。
server.on('connection', (stream) => {
console.log('someone connected!');
});
Returns a reference to the 返回对EventEmitter, so that calls can be chained.EventEmitter的引用,以便可以链接调用。
By default, event listeners are invoked in the order they are added. 默认情况下,事件侦听器按添加顺序调用。The emitter.prependListener() method can be used as an alternative to add the event listener to the beginning of the listeners array.emitter.prependListener()方法可以用作将事件侦听器添加到侦听器数组开头的替代方法。
import { EventEmitter } from 'node:events';
const myEE = new EventEmitter();
myEE.on('foo', () => console.log('a'));
myEE.prependListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
The callback function
Adds a one-time 为名为listener function for the event named eventName. The next time eventName is triggered, this listener is removed and then invoked.eventName的事件添加一次性listener函数。下次触发eventName时,将删除并调用此侦听器。
server.once('connection', (stream) => {
console.log('Ah, we have our first user!');
});
Returns a reference to the 返回对EventEmitter, so that calls can be chained.EventEmitter的引用,以便可以链接调用。
By default, event listeners are invoked in the order they are added. 默认情况下,事件侦听器按添加顺序调用。The emitter.prependOnceListener() method can be used as an alternative to add the event listener to the beginning of the listeners array.emitter.prependOnceListener()方法可以用作将事件侦听器添加到侦听器数组开头的替代方法。
import { EventEmitter } from 'node:events';
const myEE = new EventEmitter();
myEE.once('foo', () => console.log('a'));
myEE.prependOnceListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
The callback function回调函数
Adds a one-time 为名为listener function for the event named eventName. The next time eventName is triggered, this listener is removed and then invoked.eventName的事件添加一次性listener函数。下次触发eventName时,将删除并调用此侦听器。
server.once('connection', (stream) => {
console.log('Ah, we have our first user!');
});
Returns a reference to the 返回对EventEmitter, so that calls can be chained.EventEmitter的引用,以便可以链接调用。
By default, event listeners are invoked in the order they are added. The 默认情况下,事件侦听器按添加顺序调用。emitter.prependOnceListener() method can be used as an alternative to add the event listener to the beginning of the listeners array.emitter.prependOnceListener()方法可以用作将事件侦听器添加到侦听器数组开头的替代方法。
import { EventEmitter } from 'node:events';
const myEE = new EventEmitter();
myEE.once('foo', () => console.log('a'));
myEE.prependOnceListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
The callback function回调函数
Adds a one-time 为名为listener function for the event named eventName. The next time eventName is triggered, this listener is removed and then invoked.eventName的事件添加一次性listener函数。下次触发eventName时,将删除并调用此侦听器。
server.once('connection', (stream) => {
console.log('Ah, we have our first user!');
});
Returns a reference to the 返回对EventEmitter, so that calls can be chained.EventEmitter的引用,以便可以链接调用。
By default, event listeners are invoked in the order they are added. The 默认情况下,事件侦听器按添加顺序调用。emitter.prependOnceListener() method can be used as an alternative to add the event listener to the beginning of the listeners array.emitter.prependOnceListener()方法可以用作将事件侦听器添加到侦听器数组开头的替代方法。
import { EventEmitter } from 'node:events';
const myEE = new EventEmitter();
myEE.once('foo', () => console.log('a'));
myEE.prependOnceListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
The callback function回调函数
Adds the 将listener function to the beginning of the listeners array for the event named eventName. No checks are made to see if the listener has already been added. Multiple calls passing the same combination of eventName and listener will result in the listener being added, and called, multiple times.listener函数添加到名为eventName的事件的侦听器数组的开头。不检查是否已添加侦听器。传递相同eventName和listener组合的多个调用将导致listener被多次添加和调用。
server.prependListener('connection', (stream) => {
console.log('someone connected!');
});
Returns a reference to the 返回对EventEmitter, so that calls can be chained.EventEmitter的引用,以便可以链接调用。
The callback function
Adds the 将listener function to the beginning of the listeners array for the event named eventName. listener函数添加到名为eventName的事件的侦听器数组的开头。No checks are made to see if the 不检查是否已添加listener has already been added. Multiple calls passing the same combination of eventName and listener will result in the listener being added, and called, multiple times.listener。传递相同eventName和listener组合的多个调用将导致listener被多次添加和调用。
server.prependListener('connection', (stream) => {
console.log('someone connected!');
});
Returns a reference to the 返回对EventEmitter, so that calls can be chained.EventEmitter的引用,以便可以链接调用。
The callback function
Adds the 将listener function to the beginning of the listeners array for the event named eventName. No checks are made to see if the listener has already been added. Multiple calls passing the same combination of eventName and listener will result in the listener being added, and called, multiple times.listener函数添加到名为eventName的事件的侦听器数组的开头。不检查是否已添加listener。传递相同eventName和listener组合的多个调用将导致侦听器被多次添加和调用。
server.prependListener('connection', (stream) => {
console.log('someone connected!');
});
Returns a reference to the 返回对EventEmitter, so that calls can be chained.EventEmitter的引用,以便可以链接调用。
The callback function
Adds a one-time将名为listener function for the event named eventName to the beginning of the listeners array. The next time eventName is triggered, this listener is removed, and then invoked.eventName的事件的一次性listener函数添加到侦听器数组的开头。下次触发eventName时,此侦听器将被删除,然后被调用。
server.prependOnceListener('connection', (stream) => {
console.log('Ah, we have our first user!');
});
Returns a reference to the 返回对EventEmitter, so that calls can be chained.EventEmitter的引用,以便可以链接调用。
The callback function
Adds a one-time将名为listener function for the event named eventName to the beginning of the listeners array. The next time eventName is triggered, this listener is removed, and then invoked.eventName的事件的一次性侦听器函数添加到侦听器数组的开头。下次触发eventName时,此侦听器将被删除,然后被调用。
server.prependOnceListener('connection', (stream) => {
console.log('Ah, we have our first user!');
});
Returns a reference to the 返回对EventEmitter, so that calls can be chained.EventEmitter的引用,以便可以链接调用。
The callback function回调函数
Adds a one-time将名为listener function for the event named eventName to the beginning of the listeners array. The next time eventName is triggered, this listener is removed, and then invoked.eventName的事件的一次性侦听器函数添加到侦听器数组的开头。下次触发eventName时,此侦听器将被删除,然后被调用。
server.prependOnceListener('connection', (stream) => {
console.log('Ah, we have our first user!');
});
Returns a reference to the 返回对EventEmitter, so that calls can be chained.EventEmitter的引用,以便可以链接调用。
The callback function回调函数
Returns a copy of the array of listeners for the event named 返回名为eventName, including any wrappers (such as those created by .once()).eventName的事件的侦听器数组的副本,包括任何包装器(如.once()创建的包装器)。
import { EventEmitter } from 'node:events';
const emitter = new EventEmitter();
emitter.once('log', () => console.log('log once'));
// Returns a new Array with a function `onceWrapper` which has a property `listener` which contains the original listener bound above返回一个带有函数`onceWrapper`的新数组,该函数具有属性`listener`,该属性包含上面绑定的原始侦听器
const listeners = emitter.rawListeners('log');
const logFnWrapper = listeners[0];
// Logs "log once" to the console and does not unbind the `once` event将“log once”记录到控制台,并且不解除`once`事件的绑定
logFnWrapper.listener();
// Logs "log once" to the console and removes the listener将“日志一次”记录到控制台并删除侦听器
logFnWrapper();
emitter.on('log', () => console.log('log persistently'));
// Will return a new Array with a single function bound by `.on()` above将返回一个新的数组,其中包含一个由上述`on()`绑定的函数
const newListeners = emitter.rawListeners('log');
// Logs "log persistently" twice记录两次“持久日志”
newListeners[0]();
emitter.emit('log');
Removes all listeners, or those of the specified 删除所有侦听器或指定eventName.eventName的侦听器。
It is bad practice to remove listeners added elsewhere in the code, particularly when the 删除代码中其他地方添加的监听器是不好的做法,特别是当EventEmitter instance was created by some other component or module (e.g. sockets or file streams).EventEmitter实例是由其他组件或模块(例如套接字或文件流)创建的时候。
Returns a reference to the 返回对EventEmitter, so that calls can be chained.EventEmitter的引用,以便可以链接调用。
Optionalevent: string | symbol | EventKeyRemoves the specified 从名为listener from the listener array for the event named eventName.eventName的事件的侦听器数组中删除指定的listener。
const callback = (stream) => {
console.log('someone connected!');
};
server.on('connection', callback);
// ...
server.removeListener('connection', callback);
removeListener() will remove, at most, one instance of a listener from the listener array. 将从侦听器数组中最多删除一个侦听器实例。If any single listener has been added multiple times to the listener array for the specified 如果任何单个侦听器已多次添加到指定eventName, then removeListener() must be called multiple times to remove each instance.eventName的侦听器数组中,则必须多次调用removeListener()以删除每个实例。
Once an event is emitted, all listeners attached to it at the time of emitting are called in order. 一旦事件被发出,在发出时附加到它的所有侦听器都会按顺序被调用。This implies that any 这意味着在发出之后和最后一个监听器完成执行之前的任何removeListener() or removeAllListeners() calls after emitting and before the last listener finishes execution will not remove them fromemit() in progress. Subsequent events behave as expected.removeListener()或removeAllListeners()调用都不会将它们从正在进行的emit()中删除。后续事件按预期进行。
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.callbackA删除了监听器callbackB,但它仍将被调用。
// Internal listener array at time of emit [callbackA, callbackB]发出时的内部监听器数组[callbackA,callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.callbackB现在已删除。
// Internal listener array [callbackA]内部监听器数组[callbackA]
myEmitter.emit('event');
// Prints:
// A
Because listeners are managed using an internal array, calling this will change the position indices of any listener registered after the listener being removed. This will not impact the order in which listeners are called, but it means that any copies of the listener array as returned by the 由于侦听器是使用内部数组管理的,因此调用此函数将更改删除侦听器后注册的任何侦听器的位置索引。这不会影响调用监听器的顺序,但这意味着需要重新创建emitter.listeners() method will need to be recreated.emitterlisteners()方法返回的监听器数组的任何副本。
When a single function has been added as a handler multiple times for a single event (as in the example below), 当一个函数被多次添加为单个事件的处理程序时(如下例所示),removeListener() will remove the most recently added instance. In the example the once('ping') listener is removed:removeListener()将删除最近添加的实例。在该示例中,once('ping')监听器被删除:
import { EventEmitter } from 'node:events';
const ee = new EventEmitter();
function pong() {
console.log('pong');
}
ee.on('ping', pong);
ee.once('ping', pong);
ee.removeListener('ping', pong);
ee.emit('ping');
ee.emit('ping');
Returns a reference to the 返回对EventEmitter, so that calls can be chained.EventEmitter的引用,以便可以链接调用。
Removes the specified 从名为listener from the listener array for the event named eventName.eventName的事件的侦听器数组中删除指定的listener。
const callback = (stream) => {
console.log('someone connected!');
};
server.on('connection', callback);
// ...
server.removeListener('connection', callback);
removeListener() will remove, at most, one instance of a listener from the listener array. 将从侦听器数组中最多删除一个侦听器实例。If any single listener has been added multiple times to the listener array for the specified 如果任何单个侦听器已多次添加到指定eventName, then removeListener() must be called multiple times to remove each instance.eventName的侦听器数组中,则必须多次调用removeListener()以删除每个实例。
Once an event is emitted, all listeners attached to it at the time of emitting are called in order. This implies that any 一旦事件被发出,在发出时附加到它的所有侦听器都会按顺序被调用。这意味着在发出之后和最后一个监听器完成执行之前的任何removeListener() or removeAllListeners() calls after emitting and before the last listener finishes execution will not remove them fromemit() in progress. Subsequent events behave as expected.removeListener()或removeAllListeners()调用都不会将它们从正在进行的emit()中删除。后续事件按预期进行。
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
Because listeners are managed using an internal array, calling this will change the position indices of any listener registered after the listener being removed. This will not impact the order in which listeners are called, but it means that any copies of the listener array as returned by the 由于侦听器是使用内部数组管理的,因此调用此函数将更改删除侦听器后注册的任何侦听器的位置索引。这不会影响调用监听器的顺序,但这意味着需要重新创建emitter.listeners() method will need to be recreated.emitter.listeners()方法返回的监听器数组的任何副本。
When a single function has been added as a handler multiple times for a single event (as in the example below), 当一个函数被多次添加为单个事件的处理程序时(如下例所示),removeListener() will remove the most recently added instance. In the example the once('ping') listener is removed:removeListener()将删除最近添加的实例。在该示例中,once('ping')监听器被删除:
import { EventEmitter } from 'node:events';
const ee = new EventEmitter();
function pong() {
console.log('pong');
}
ee.on('ping', pong);
ee.once('ping', pong);
ee.removeListener('ping', pong);
ee.emit('ping');
ee.emit('ping');
Returns a reference to the 返回对EventEmitter, so that calls can be chained.EventEmitter的引用,以便可以链接调用。
Removes the specified 从名为listener from the listener array for the event named eventName.eventName的事件的侦听器数组中删除指定的listener。
const callback = (stream) => {
console.log('someone connected!');
};
server.on('connection', callback);
// ...
server.removeListener('connection', callback);
removeListener() will remove, at most, one instance of a listener from the listener array. If any single listener has been added multiple times to the listener array for the specified 将从侦听器数组中最多删除一个侦听器实例。如果任何单个侦听器已多次添加到指定eventName, then removeListener() must be called multiple times to remove each instance.eventName的侦听器数组中,则必须多次调用removeListener()以删除每个实例。
Once an event is emitted, all listeners attached to it at the time of emitting are called in order. 一旦事件被发出,在发出时附加到它的所有侦听器都会按顺序被调用。This implies that any 这意味着在发出之后和最后一个监听器完成执行之前的任何removeListener() or removeAllListeners() calls after emitting and before the last listener finishes execution will not remove them fromemit() in progress. Subsequent events behave as expected.removeListener()或removeAllListeners()调用都不会将它们从正在进行的emit()中删除。后续事件按预期进行。
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]发出时的内部监听器数组[callbackA,callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.callbackB现在已删除。
// Internal listener array [callbackA]内部监听器数组[callbackA]
myEmitter.emit('event');
// Prints:
// A
Because listeners are managed using an internal array, calling this will change the position indices of any listener registered after the listener being removed. 由于侦听器是使用内部数组管理的,因此调用此函数将更改删除侦听器后注册的任何侦听器的位置索引。This will not impact the order in which listeners are called, but it means that any copies of the listener array as returned by the 这不会影响调用监听器的顺序,但这意味着需要重新创建emitter.listeners() method will need to be recreated.emitter.listeners()方法返回的监听器数组的任何副本。
When a single function has been added as a handler multiple times for a single event (as in the example below), 当一个函数被多次添加为单个事件的处理程序时(如下例所示),removeListener() will remove the most recently added instance. In the example the once('ping') listener is removed:removeListener()将删除最近添加的实例。在该示例中,once('ping')监听器被删除:
import { EventEmitter } from 'node:events';
const ee = new EventEmitter();
function pong() {
console.log('pong');
}
ee.on('ping', pong);
ee.once('ping', pong);
ee.removeListener('ping', pong);
ee.emit('ping');
ee.emit('ping');
Returns a reference to the 返回对EventEmitter, so that calls can be chained.EventEmitter的引用,以便可以链接调用。
By default 默认情况下,如果为特定事件添加了10个以上的监听器,EventEmitters will print a warning if more than 10 listeners are added for a particular event. EventEmitter将打印警告。This is a useful default that helps finding memory leaks. 这是一个有用的默认值,有助于查找内存泄漏。The emitter.setMaxListeners() method allows the limit to be modified for this specific EventEmitter instance. The value can be set to Infinity (or 0) to indicate an unlimited number of listeners.emitter.setMaxListeners()方法允许修改此特定EventEmitter实例的限制。该值可以设置为Infinity(或0),以表示侦听器的数量不受限制。
Returns a reference to the 返回对EventEmitter, so that calls can be chained.EventEmitter的引用,以便可以链接调用。
Creates a new ClientSession. When using the returned session in an operation a corresponding ServerSession will be created.创建新的ClientSession。在操作中使用返回的会话时,将创建相应的ServerSession。
Optionaloptions: ClientSessionOptionsCreate a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this cluster. Will ignore all changes to system collections, as well as the local, admin, and config databases.创建新的更改流,观察此集群中的新更改(插入、更新、替换、删除和无效)。将忽略对系统集合以及本地、管理和配置数据库的所有更改。
Type of the data being detected by the change stream更改流检测到的数据类型
Type of the whole change stream document emitted发出的整个变更流文档的类型
An array of pipeline stages through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents.一系列管道阶段,通过这些阶段传递变更流文档。这允许筛选(使用$match)和操纵更改流文档。
Optional settings for the command命令的可选设置
watch() accepts two generic arguments for distinct use cases:watch()为不同的用例接受两个泛型参数:
In iterator mode, if a next() call throws a timeout error, it will attempt to resume the change stream. The next call can just be retried after this succeeds.在迭代器模式下,如果next()调用抛出超时错误,它将尝试恢复更改流。此操作成功后,可以重试下一个调用。
const changeStream = collection.watch([], { timeoutMS: 100 });
try {
await changeStream.next();
} catch (e) {
if (e instanceof MongoOperationTimeoutError && !changeStream.closed) {
await changeStream.next();
}
throw e;
}
In emitter mode, if the change stream goes 在发射器模式下,如果更改流超时过了timeoutMS without emitting a change event, it will emit an error event that returns a MongoOperationTimeoutError, but will not close the change stream unless the resume attempt fails. timeoutMS而不发出更改事件,它将发出一个错误事件,返回MongoOperationTimeoutError,但除非恢复尝试失败,否则不会关闭更改流。There is no need to re-establish change listeners as this will automatically continue emitting change events once the resume attempt completes.无需重新建立更改侦听器,因为一旦恢复尝试完成,它将自动继续发出更改事件。
const changeStream = collection.watch([], { timeoutMS: 100 });
changeStream.on('change', console.log);
changeStream.on('error', e => {
if (e instanceof MongoOperationTimeoutError && !changeStream.closed) {
// do nothing
} else {
changeStream.close();
}
});
A convenience method for creating and handling the clean up of a ClientSession. The session will always be ended when the executor finishes.一种创建和处理ClientSession清理的便利方法。当执行者完成时,会话将始终结束。
An executor function that all operations using the provided session must be invoked in一个执行器函数,必须在其中调用使用所提供会话的所有操作
StaticaddListens once to the 在提供的abort event on the provided signal.signal上监听一次中止事件。
Listening to the 监听中止信号上的abort event on abort signals is unsafe and may lead to resource leaks since another third party with the signal can call e.stopImmediatePropagation(). Unfortunately Node.js cannot change this since it would violate the web standard. Additionally, the original API makes it easy to forget to remove listeners.abort事件是不安全的,可能会导致资源泄漏,因为另一个拥有该信号的第三方可以调用e.stopImmediatePropagation()。不幸的是,Node.js无法改变这一点,因为它违反了web标准。此外,最初的API使您很容易忘记删除侦听器。
This API allows safely using 这个API允许在Node.js API中安全地使用AbortSignals in Node.js APIs by solving these two issues by listening to the event such that stopImmediatePropagation does not prevent the listener from running.AbortSignal,方法是通过侦听事件来解决这两个问题,这样stopImmediatePropagation就不会阻止侦听器运行。
Returns a disposable so that it may be unsubscribed from more easily.返回disposable,以便更容易取消订阅。
import { addAbortListener } from 'node:events';
function example(signal) {
let disposable;
try {
signal.addEventListener('abort', (e) => e.stopImmediatePropagation());
disposable = addAbortListener(signal, (e) => {
// Do something when signal is aborted.
});
} finally {
disposable?.[Symbol.dispose]();
}
}
Disposable that removes the 删除abort listener.abort侦听器的disposable。
StaticconnectCreates a new MongoClient instance and immediately connects it to MongoDB. This convenience method combines 创建一个新的MongoClient实例,并立即将其连接到MongoDB。这种方便的方法将new MongoClient(url, options) and client.connect() in a single step.new MongoClient(url, options)和client.connect()组合在一个步骤中。
Connect can be helpful to detect configuration issues early by validating:Connect可以通过验证以下内容来帮助及早检测配置问题:
Optionaloptions: MongoClientOptionsA promise that resolves to the same MongoClient instance once connected连接后解析为同一MongoClient实例的promise
Connection is Optional:连接是可选的: Calling 调用connect is optional since any operation method (find, insertOne, etc.) will automatically perform these same validation steps if the client is not already connected. However, explicitly calling connect can make sense for:connect是可选的,因为如果客户端尚未连接,任何操作方法(find、insertOne等)都会自动执行这些相同的验证步骤。但是,显式调用connect可能对以下情况有意义:
StaticgetReturns a copy of the array of listeners for the event named 返回名为eventName.eventName的事件的侦听器数组的副本。
For 对于EventEmitters this behaves exactly the same as calling .listeners on the emitter.EventEmitter,这与调用发射器上的.listeners完全相同。
For 对于EventTargets this is the only way to get the event listeners for the event target. This is useful for debugging and diagnostic purposes.EventTarget,这是获取事件目标的事件侦听器的唯一方法。这对于调试和诊断非常有用。
import { getEventListeners, EventEmitter } from 'node:events';
{
const ee = new EventEmitter();
const listener = () => console.log('Events are fun');
ee.on('foo', listener);
console.log(getEventListeners(ee, 'foo')); // [ [Function: listener] ]
}
{
const et = new EventTarget();
const listener = () => console.log('Events are fun');
et.addEventListener('foo', listener);
console.log(getEventListeners(et, 'foo')); // [ [Function: listener] ]
}
StaticgetReturns the currently set max amount of listeners.返回当前设置的最大侦听器数量。
For 对于EventEmitters this behaves exactly the same as calling .getMaxListeners on the emitter.EventEmitter,这与在发射器上调用getMaxListeners的行为完全相同。
For 对于EventTargets this is the only way to get the max event listeners for the event target. If the number of event handlers on a single EventTarget exceeds the max set, the EventTarget will print a warning.EventTarget,这是获取事件目标的最大事件侦听器的唯一方法。如果单个EventTarget上的事件处理程序数量超过设置的最大值,EventTarget将打印警告。
import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events';
{
const ee = new EventEmitter();
console.log(getMaxListeners(ee)); // 10
setMaxListeners(11, ee);
console.log(getMaxListeners(ee)); // 11
}
{
const et = new EventTarget();
console.log(getMaxListeners(et)); // 10
setMaxListeners(11, et);
console.log(getMaxListeners(et)); // 11
}
StaticlistenerA class method that returns the number of listeners for the given 一个类方法,返回在给定eventName registered on the given emitter.emitter上注册的给定eventName的侦听器数量。
import { EventEmitter, listenerCount } from 'node:events';
const myEmitter = new EventEmitter();
myEmitter.on('event', () => {});
myEmitter.on('event', () => {});
console.log(listenerCount(myEmitter, 'event'));
// Prints: 2
The emitter to query要查询的发射器
The event name事件名称
Staticonimport { on, EventEmitter } from 'node:events';
import process from 'node:process';
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});
for await (const event of on(ee, 'foo')) {
// The execution of this inner block is synchronous and it processes one event at a time (even with await). Do not use if concurrent execution is required.这个内部块的执行是同步的,它一次处理一个事件(即使有wait)。如果需要并发执行,请不要使用。
console.log(event); // prints ['bar'] [42]
}
// Unreachable here此处无法访问
Returns an 返回一个迭代AsyncIterator that iterates eventName events. eventName事件的AsyncIterator。It will throw if the 如果EventEmitter emits 'error'. It removes all listeners when exiting the loop. The value returned by each iteration is an array composed of the emitted event arguments.EventEmitter发出'error',它将抛出。退出循环时,它会删除所有侦听器。每次迭代返回的value是由发出的事件参数组成的数组。
An AbortSignal can be used to cancel waiting on events:AbortSignal可用于取消等待事件:
import { on, EventEmitter } from 'node:events';
import process from 'node:process';
const ac = new AbortController();
(async () => {
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});
for await (const event of on(ee, 'foo', { signal: ac.signal })) {
// The execution of this inner block is synchronous and it processes one event at a time (even with await). Do not use if concurrent execution is required.这个内部块的执行是同步的,它一次处理一个事件(即使有wait)。如果需要并发执行,请不要使用。
console.log(event); // prints ['bar'] [42]
}
// Unreachable here此处无法访问
})();
process.nextTick(() => ac.abort());
Use the 使用close option to specify an array of event names that will end the iteration:close选项指定将结束迭代的事件名称数组:
import { on, EventEmitter } from 'node:events';
import process from 'node:process';
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
ee.emit('close');
});
for await (const event of on(ee, 'foo', { close: ['close'] })) {
console.log(event); // prints ['bar'] [42]
}
// the loop will exit after 'close' is emitted发出'close'后,循环将退出
console.log('done'); // prints 'done'
Optionaloptions: StaticEventEmitterIteratorOptionsAn 迭代发射器发出的AsyncIterator that iterates eventName events emitted by the emittereventName事件的AsyncIterator
Optionaloptions: StaticEventEmitterIteratorOptionsStaticonceCreates a 创建一个Promise that is fulfilled when the EventEmitter emits the given event or that is rejected if the EventEmitter emits 'error' while waiting. The Promise will resolve with an array of all the arguments emitted to the given event.Promise,当EventEmitter发出给定事件时,该Promise会被满足;如果EventEmitter在等待时发出'error',则该Promise将被拒绝。Promise将使用向给定事件发出的所有参数的数组进行解析。
This method is intentionally generic and works with the web platform EventTarget interface, which has no special此方法有意通用,适用于web平台EventTarget接口,该接口没有特殊的'error' event semantics and does not listen to the 'error' event.'error'事件语义,也不监听'error'的事件。
import { once, EventEmitter } from 'node:events';
import process from 'node:process';
const ee = new EventEmitter();
process.nextTick(() => {
ee.emit('myevent', 42);
});
const [value] = await once(ee, 'myevent');
console.log(value);
const err = new Error('kaboom');
process.nextTick(() => {
ee.emit('error', err);
});
try {
await once(ee, 'myevent');
} catch (err) {
console.error('error happened', err);
}
The special handling of the 仅当'error' event is only used when events.once() is used to wait for another event. events.once()用于等待另一个事件时,才使用'error'事件的特殊处理。If 如果events.once() is used to wait for the 'error' event itself, then it is treated as any other kind of event without special handling:events.once()用于等待'error'事件本身,那么它将被视为任何其他类型的事件,而无需特殊处理:
import { EventEmitter, once } from 'node:events';
const ee = new EventEmitter();
once(ee, 'error')
.then(([err]) => console.log('ok', err.message))
.catch((err) => console.error('error', err.message));
ee.emit('error', new Error('boom'));
// Prints: ok boom
An AbortSignal can be used to cancel waiting for the event:AbortSignal可用于取消等待事件:
import { EventEmitter, once } from 'node:events';
const ee = new EventEmitter();
const ac = new AbortController();
async function foo(emitter, event, signal) {
try {
await once(emitter, event, { signal });
console.log('event emitted!');
} catch (error) {
if (error.name === 'AbortError') {
console.error('Waiting for the event was canceled!');
} else {
console.error('There was an error', error.message);
}
}
}
foo(ee, 'foo', ac.signal);
ac.abort(); // Abort waiting for the event中止等待事件
ee.emit('foo'); // Prints: Waiting for the event was canceled!打印:等待活动已取消!
Optionaloptions: StaticEventEmitterOptionsOptionaloptions: StaticEventEmitterOptionsStaticsetimport { setMaxListeners, EventEmitter } from 'node:events';
const target = new EventTarget();
const emitter = new EventEmitter();
setMaxListeners(5, target, emitter);
Optionaln: number
A non-negative number. The maximum number of listeners per 一个非负数。每个EventTarget event.EventTarget事件的最大侦听器数。
Rest...eventTargets: (EventEmitter<DefaultEventMap> | EventTarget)[]
Zero or more {EventTarget} or {EventEmitter} instances. If none are specified, 零个或多个n is set as the default max for all newly created {EventTarget} and {EventEmitter}
objects.{EventTarget}或{EventTarget}实例。如果没有指定,则将n设置为所有新创建的{EventTarget}和{EventEmitter}对象的默认最大值。
The MongoClient class is a class that allows for making Connections to MongoDB.MongoClient类是一个允许连接到MongoDB的类。NOTE:
The programmatically provided options take precedence over the URI options.编程提供的选项优先于URI选项。Remarks
A MongoClient is the entry point to connecting to a MongoDB server.MongoClient是连接到MongoDB服务器的入口点。It handles a multitude of features on your application's behalf:它代表应用程序处理大量功能:Server Host Connection Configuration服务器主机连接配置: A MongoClient is responsible for reading TLS cert, ca, and crl files if provided.:MongoClient负责读取TLS证书、ca和crl文件(如果提供)。SRV Record PollingSRV记录轮询: A ":mongodb+srv" style connection string is used to have the MongoClient resolve DNS SRV records of all server hostnames which the driver periodically monitors for changes and adjusts its current view of hosts correspondingly.mongodb+srv样式的连接字符串用于让MongoClient解析所有服务器主机名的DNS srv记录,驱动程序会定期监视这些记录的更改,并相应地调整其当前的主机视图。Server Monitoring服务器监控: The MongoClient automatically keeps monitoring the health of server nodes in your cluster to reach out to the correct and lowest latency one available.:MongoClient会自动监控集群中服务器节点的健康状况,以找到正确且延迟最低的节点。Connection Pooling连接池: To avoid paying the cost of rebuilding a connection to the server on every operation the MongoClient keeps idle connections preserved for reuse.:为了避免在每次操作时都要支付重建与服务器连接的费用,MongoClient会保留空闲连接以供重用。Session Pooling会话池: The MongoClient creates logical sessions that enable retryable writes, causal consistency, and transactions. It handles pooling these sessions for reuse in subsequent operations.:MongoClient创建逻辑会话,实现可重试写入、因果一致性和事务。它处理这些会话的池化,以便在后续操作中重用。Cursor Operations游标操作: A MongoClient's cursors use the health monitoring system to send the request for more documents to the same server the query began on.:MongoClient的游标使用健康监控系统将更多文档的请求发送到查询开始的同一服务器。Mongocryptd processMongocryptd进程: When using auto encryption, a MongoClient will launch a:使用自动加密时,如果mongocrypt共享库未被使用,MongoClient将启动一个mongocryptd实例来处理加密。mongocryptdinstance for handling encryption if the mongocrypt shared library isn't in use.There are many more features of a MongoClient that are not listed above.MongoClient还有很多上面没有列出的功能。In order to enable these features, a number of asynchronous Node.js resources are established by the driver: Timers, FS Requests, Sockets, etc. For details on cleanup, please refer to the MongoClient为了启用这些功能,驱动程序建立了许多异步Node.js资源:定时器、FS请求、套接字等。有关清理的详细信息,请参阅MongoClientclose()documentation.close()文档。Example示例