Class MongoClient

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选项。

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 mongocryptd instance for handling encryption if the mongocrypt shared library isn't in use.:使用自动加密时,如果mongocrypt共享库未被使用,MongoClient将启动一个mongocryptd实例来处理加密。

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 close() documentation.为了启用这些功能,驱动程序建立了许多异步Node.js资源:定时器、FS请求、套接字等。有关清理的详细信息,请参阅MongoClient close()文档。

import { MongoClient } from 'mongodb';
// Enable command monitoring for debugging启用调试命令监视
const client = new MongoClient('mongodb://localhost:27017?appName=mflix', { monitorCommands: true });

Hierarchy (view full)

Implements

  • AsyncDisposable

Constructors构造函数

Properties属性

options: Readonly<Omit<MongoOptions,
    | "ca"
    | "cert"
    | "crl"
    | "key"
    | "driverInfo"
    | "monitorCommands">> & Pick<MongoOptions,
    | "ca"
    | "cert"
    | "crl"
    | "key"
    | "driverInfo"
    | "monitorCommands"> & {}

The consolidate, parsed, transformed and merged options.整合、解析、转换和合并选项。

captureRejections: boolean

Value: boolean

Change the default captureRejections option on all new EventEmitter objects.更改所有新EventEmitter对象的默认captureRejections选项。

v13.4.0, v12.16.0

captureRejectionSymbol: typeof captureRejectionSymbol

Value: Symbol.for('nodejs.rejection')

See how to write a custom rejection handler.了解如何编写自定义拒绝处理程序

v13.4.0, v12.16.0

defaultMaxListeners: number

By 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 allEventEmitter 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')检查发出的警告,并将具有额外的emittertypecount属性,分别引用事件发射器实例、事件名称和附加侦听器的数量。Its name property is set to 'MaxListenersExceededWarning'.name属性设置为'MaxListenersExceededWarning'

v0.11.2

errorMonitor: typeof errorMonitor

This 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'侦听器,该进程仍将崩溃。

v13.6.0, v12.17.0

Accessors

Methods

  • Type Parameters

    • K

    Parameters

    • error: Error
    • event: string | symbol
    • Rest...args: AnyRest

    Returns void

  • Alias for emitter.on(eventName, listener).

    Type Parameters类型参数

    • EventKey extends
          | "error"
          | "timeout"
          | "close"
          | "open"
          | "serverOpening"
          | "serverClosed"
          | "serverDescriptionChanged"
          | "topologyOpening"
          | "topologyClosed"
          | "topologyDescriptionChanged"
          | "connectionPoolCreated"
          | "connectionPoolClosed"
          | "connectionPoolCleared"
          | "connectionPoolReady"
          | "connectionCreated"
          | "connectionReady"
          | "connectionClosed"
          | "connectionCheckOutStarted"
          | "connectionCheckOutFailed"
          | "connectionCheckedOut"
          | "connectionCheckedIn"
          | "commandStarted"
          | "commandSucceeded"
          | "commandFailed"
          | "serverHeartbeatStarted"
          | "serverHeartbeatSucceeded"
          | "serverHeartbeatFailed"

    Parameters

    Returns this

    v0.1.26

  • Alias for emitter.on(eventName, listener).

    Parameters

    Returns this

    v0.1.26

  • Alias for emitter.on(eventName, listener).

    Parameters

    Returns this

    v0.1.26

  • Append metadata to the client metadata after instantiation.实例化后将元数据附加到客户端元数据。

    Parameters

    • driverInfo: DriverInfo

      Information about the application or library.有关应用程序或库的信息。

    Returns void

  • Executes a client bulk write operation, available on server 8.0+.执行客户端批量写入操作,可在服务器8.0+上使用。

    Type Parameters

    Parameters

    Returns Promise<ClientBulkWriteResult>

    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 MongoClient class documentation for a high level overview of the client's key features and responsibilities.close方法清除并关闭其生命周期由MongoClient管理的所有资源。请参阅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() 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方法不处理用户显式创建的资源的清理。任何用户创建的具有自己的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-side:客户端:
      • Close in-use connections关闭正在使用的连接: Any connections that are currently waiting on a response from the server will be closed. This is performed first to avoid reaching the next step (server-side clean up) and having no available connections to check out.:当前正在等待服务器响应的任何连接都将被关闭。首先执行此操作是为了避免进入下一步(服务器端清理)并且没有可用的连接可供签出。
        • Ideal: All operations have been awaited or cancelled, and the outcomes, regardless of success or failure, have been processed before closing the client servicing the operation.:所有操作都已等待或取消,在关闭为操作提供服务的客户端之前,无论成功还是失败,结果都已得到处理。
        • Pitfall: When 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握手和身份验证步骤为代价的。
    • Server-side:服务器端:
      • Close active cursors关闭活动游标: All cursors that haven't been completed will have a killCursor operation sent to the server they were initialized on, freeing the server-side resource.:所有尚未完成的游标都将向初始化它们的服务器发送killCursor操作,从而释放服务器端资源。
        • Ideal理想: Cursors are explicitly closed or completed before client.close() is called.:游标在调用client.close()之前显式关闭或完成。
        • Pitfall陷阱: killCursors may have to build a new connection if the in-use closure ended all pooled connections.killCursor可能必须建立一个新的连接,如果正在使用的闭包结束了所有池连接。
      • End active sessions结束活动会话: In-use sessions created with client.startSession() or client.withSession() or implicitly by the driver will have their .endSession() method called. :使用client.startSession()client.withSession()创建的或由驱动程序隐式创建的在用会话将调用其.endSession()方法。Contrary to the name of the method, endSession() returns the session to the client's pool of sessions rather than end them on the server.与方法的名称相反,endSession()将会话返回到客户端的会话池,而不是在服务器上结束它们。
        • Ideal理想: Transaction outcomes are awaited and their corresponding explicit sessions are ended before client.close() is called.:等待事务结果,并在调用client.close()之前结束其相应的显式会话。
        • Pitfall陷阱: This step aborts in-progress transactions. It is advisable to observe the outcome of a transaction before closing your client.此步骤中止正在进行的事务。建议在关闭客户之前观察事务结果。
      • End all pooled sessions结束所有集合会话: The endSessions command with all session IDs the client has pooled is sent to the server to inform the cluster it can clean them up.:将带有客户端已池化的所有会话ID的endSessions命令发送到服务器,通知集群可以清理它们。
        • Ideal理想: No user intervention is expected.:不需要用户干预。
        • Pitfall陷阱: None.:没有。

    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事件循环有关。

    • Client-side (again):客户端(再次):
      • Stop all server monitoring停止所有服务器监控: Connections kept live for detecting cluster changes and roundtrip time measurements are shutdown.:连接保持活动状态以检测集群变化,往返时间测量值关闭。
      • Close all pooled connections关闭所有池连接: Each server node in the cluster has a corresponding connection pool and all connections in the pool are closed. Any operations waiting to check out a connection will have an error thrown instead of a connection returned.:群集中的每个服务器节点都有一个相应的连接池,池中的所有连接都是关闭的。任何等待签出连接的操作都会抛出错误,而不是返回连接。
      • Clear out server selection queue清除服务器选择队列: Any operations that are in the process of waiting for a server to be selected will have an error thrown instead of a server returned.:任何正在等待选择服务器的操作都会抛出错误,而不是返回服务器。
      • Close encryption-related resources关闭加密相关资源: An internal MongoClient created for communicating with 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优雅地退出。

    Parameters

    • _force: boolean = false

      currently an unused flag that has no effect. Defaults to false.当前为无效的未使用标志。默认为false

    Returns Promise<void>

  • 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静态方法文档。

    Returns Promise<MongoClient>

  • Create a new Db instance sharing the current socket connections.创建一个共享当前套接字连接的新Db实例。

    Parameters

    • 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构造的可选设置

    Returns Db

  • 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的第一个监听器事件

    Type Parameters类型参数

    • EventKey extends
          | "error"
          | "timeout"
          | "close"
          | "open"
          | "serverOpening"
          | "serverClosed"
          | "serverDescriptionChanged"
          | "topologyOpening"
          | "topologyClosed"
          | "topologyDescriptionChanged"
          | "connectionPoolCreated"
          | "connectionPoolClosed"
          | "connectionPoolCleared"
          | "connectionPoolReady"
          | "connectionCreated"
          | "connectionReady"
          | "connectionClosed"
          | "connectionCheckOutStarted"
          | "connectionCheckOutFailed"
          | "connectionCheckedOut"
          | "connectionCheckedIn"
          | "commandStarted"
          | "commandSucceeded"
          | "commandFailed"
          | "serverHeartbeatStarted"
          | "serverHeartbeatSucceeded"
          | "serverHeartbeatFailed"

    Parameters

    Returns boolean

    v0.1.26

  • 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 string[]

    v6.0.0

  • 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 number

    v1.0.0

  • 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,它将返回在事件监听器列表中找到监听器的次数。

    Type Parameters

    • EventKey extends
          | "error"
          | "timeout"
          | "close"
          | "open"
          | "serverOpening"
          | "serverClosed"
          | "serverDescriptionChanged"
          | "topologyOpening"
          | "topologyClosed"
          | "topologyDescriptionChanged"
          | "connectionPoolCreated"
          | "connectionPoolClosed"
          | "connectionPoolCleared"
          | "connectionPoolReady"
          | "connectionCreated"
          | "connectionReady"
          | "connectionClosed"
          | "connectionCheckOutStarted"
          | "connectionCheckOutFailed"
          | "connectionCheckedOut"
          | "connectionCheckedIn"
          | "commandStarted"
          | "commandSucceeded"
          | "commandFailed"
          | "serverHeartbeatStarted"
          | "serverHeartbeatSucceeded"
          | "serverHeartbeatFailed"

    Parameters

    Returns number

    v3.2.0

  • 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] ]

    Type Parameters

    • EventKey extends
          | "error"
          | "timeout"
          | "close"
          | "open"
          | "serverOpening"
          | "serverClosed"
          | "serverDescriptionChanged"
          | "topologyOpening"
          | "topologyClosed"
          | "topologyDescriptionChanged"
          | "connectionPoolCreated"
          | "connectionPoolClosed"
          | "connectionPoolCleared"
          | "connectionPoolReady"
          | "connectionCreated"
          | "connectionReady"
          | "connectionClosed"
          | "connectionCheckOutStarted"
          | "connectionCheckOutFailed"
          | "connectionCheckedOut"
          | "connectionCheckedIn"
          | "commandStarted"
          | "commandSucceeded"
          | "commandFailed"
          | "serverHeartbeatStarted"
          | "serverHeartbeatSucceeded"
          | "serverHeartbeatFailed"

    Parameters

    Returns MongoClientEvents[EventKey][]

    v0.1.26

  • Alias for emitter.removeListener().emitter.removeListener()的别名。

    Type Parameters

    • EventKey extends
          | "error"
          | "timeout"
          | "close"
          | "open"
          | "serverOpening"
          | "serverClosed"
          | "serverDescriptionChanged"
          | "topologyOpening"
          | "topologyClosed"
          | "topologyDescriptionChanged"
          | "connectionPoolCreated"
          | "connectionPoolClosed"
          | "connectionPoolCleared"
          | "connectionPoolReady"
          | "connectionCreated"
          | "connectionReady"
          | "connectionClosed"
          | "connectionCheckOutStarted"
          | "connectionCheckOutFailed"
          | "connectionCheckedOut"
          | "connectionCheckedIn"
          | "commandStarted"
          | "commandSucceeded"
          | "commandFailed"
          | "serverHeartbeatStarted"
          | "serverHeartbeatSucceeded"
          | "serverHeartbeatFailed"

    Parameters

    Returns this

    v10.0.0

  • Alias for emitter.removeListener().emitter.removeListener()的别名。

    Parameters

    Returns this

    v10.0.0

  • Alias for emitter.removeListener().emitter.removeListener()的别名。

    Parameters

    Returns this

    v10.0.0

  • 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的事件的侦听器数组末尾。不检查是否已添加侦听器。传递相同eventNamelistener组合的多个调用将导致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

    Type Parameters

    • EventKey extends
          | "error"
          | "timeout"
          | "close"
          | "open"
          | "serverOpening"
          | "serverClosed"
          | "serverDescriptionChanged"
          | "topologyOpening"
          | "topologyClosed"
          | "topologyDescriptionChanged"
          | "connectionPoolCreated"
          | "connectionPoolClosed"
          | "connectionPoolCleared"
          | "connectionPoolReady"
          | "connectionCreated"
          | "connectionReady"
          | "connectionClosed"
          | "connectionCheckOutStarted"
          | "connectionCheckOutFailed"
          | "connectionCheckedOut"
          | "connectionCheckedIn"
          | "commandStarted"
          | "commandSucceeded"
          | "commandFailed"
          | "serverHeartbeatStarted"
          | "serverHeartbeatSucceeded"
          | "serverHeartbeatFailed"

    Parameters

    Returns this

    v0.1.101

  • 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。传递相同eventNamelistener组合的多个调用将导致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

    Parameters

    • event: CommonEvents
    • listener: ((eventName: string | symbol, listener: GenericListener) => void)

      The callback function

        • (eventName, listener): void
        • Parameters

          Returns void

    Returns this

    v0.1.101

  • 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。传递相同eventNamelistener组合的多个调用将导致侦听器被多次添加和调用。

    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

    Parameters

    Returns this

    v0.1.101

  • 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

    Type Parameters

    • EventKey extends
          | "error"
          | "timeout"
          | "close"
          | "open"
          | "serverOpening"
          | "serverClosed"
          | "serverDescriptionChanged"
          | "topologyOpening"
          | "topologyClosed"
          | "topologyDescriptionChanged"
          | "connectionPoolCreated"
          | "connectionPoolClosed"
          | "connectionPoolCleared"
          | "connectionPoolReady"
          | "connectionCreated"
          | "connectionReady"
          | "connectionClosed"
          | "connectionCheckOutStarted"
          | "connectionCheckOutFailed"
          | "connectionCheckedOut"
          | "connectionCheckedIn"
          | "commandStarted"
          | "commandSucceeded"
          | "commandFailed"
          | "serverHeartbeatStarted"
          | "serverHeartbeatSucceeded"
          | "serverHeartbeatFailed"

    Parameters

    Returns this

    v0.3.0

  • 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

    Parameters

    • event: CommonEvents
    • listener: ((eventName: string | symbol, listener: GenericListener) => void)

      The callback function回调函数

        • (eventName, listener): void
        • Parameters

          Returns void

    Returns this

    v0.3.0

  • 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

    Parameters

    • event: string | symbol
    • listener: GenericListener

      The callback function回调函数

    Returns this

    v0.3.0

  • 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的事件的侦听器数组的开头。不检查是否已添加侦听器。传递相同eventNamelistener组合的多个调用将导致listener被多次添加和调用。

    server.prependListener('connection', (stream) => {
    console.log('someone connected!');
    });

    Returns a reference to the EventEmitter, so that calls can be chained.返回对EventEmitter的引用,以便可以链接调用。

    Type Parameters

    • EventKey extends
          | "error"
          | "timeout"
          | "close"
          | "open"
          | "serverOpening"
          | "serverClosed"
          | "serverDescriptionChanged"
          | "topologyOpening"
          | "topologyClosed"
          | "topologyDescriptionChanged"
          | "connectionPoolCreated"
          | "connectionPoolClosed"
          | "connectionPoolCleared"
          | "connectionPoolReady"
          | "connectionCreated"
          | "connectionReady"
          | "connectionClosed"
          | "connectionCheckOutStarted"
          | "connectionCheckOutFailed"
          | "connectionCheckedOut"
          | "connectionCheckedIn"
          | "commandStarted"
          | "commandSucceeded"
          | "commandFailed"
          | "serverHeartbeatStarted"
          | "serverHeartbeatSucceeded"
          | "serverHeartbeatFailed"

    Parameters

    Returns this

    v6.0.0

  • 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。传递相同eventNamelistener组合的多个调用将导致listener被多次添加和调用。

    server.prependListener('connection', (stream) => {
    console.log('someone connected!');
    });

    Returns a reference to the EventEmitter, so that calls can be chained.返回对EventEmitter的引用,以便可以链接调用。

    Parameters

    • event: CommonEvents
    • listener: ((eventName: string | symbol, listener: GenericListener) => void)

      The callback function

        • (eventName, listener): void
        • Parameters

          Returns void

    Returns this

    v6.0.0

  • 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。传递相同eventNamelistener组合的多个调用将导致侦听器被多次添加和调用。

    server.prependListener('connection', (stream) => {
    console.log('someone connected!');
    });

    Returns a reference to the EventEmitter, so that calls can be chained.返回对EventEmitter的引用,以便可以链接调用。

    Parameters

    Returns this

    v6.0.0

  • Adds a one-timelistener 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的引用,以便可以链接调用。

    Type Parameters

    • EventKey extends
          | "error"
          | "timeout"
          | "close"
          | "open"
          | "serverOpening"
          | "serverClosed"
          | "serverDescriptionChanged"
          | "topologyOpening"
          | "topologyClosed"
          | "topologyDescriptionChanged"
          | "connectionPoolCreated"
          | "connectionPoolClosed"
          | "connectionPoolCleared"
          | "connectionPoolReady"
          | "connectionCreated"
          | "connectionReady"
          | "connectionClosed"
          | "connectionCheckOutStarted"
          | "connectionCheckOutFailed"
          | "connectionCheckedOut"
          | "connectionCheckedIn"
          | "commandStarted"
          | "commandSucceeded"
          | "commandFailed"
          | "serverHeartbeatStarted"
          | "serverHeartbeatSucceeded"
          | "serverHeartbeatFailed"

    Parameters

    Returns this

    v6.0.0

  • Adds a one-timelistener 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的引用,以便可以链接调用。

    Parameters

    • event: CommonEvents
    • listener: ((eventName: string | symbol, listener: GenericListener) => void)

      The callback function回调函数

        • (eventName, listener): void
        • Parameters

          Returns void

    Returns this

    v6.0.0

  • Adds a one-timelistener 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的引用,以便可以链接调用。

    Parameters

    • event: string | symbol
    • listener: GenericListener

      The callback function回调函数

    Returns this

    v6.0.0

  • 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');

    Type Parameters

    • EventKey extends
          | "error"
          | "timeout"
          | "close"
          | "open"
          | "serverOpening"
          | "serverClosed"
          | "serverDescriptionChanged"
          | "topologyOpening"
          | "topologyClosed"
          | "topologyDescriptionChanged"
          | "connectionPoolCreated"
          | "connectionPoolClosed"
          | "connectionPoolCleared"
          | "connectionPoolReady"
          | "connectionCreated"
          | "connectionReady"
          | "connectionClosed"
          | "connectionCheckOutStarted"
          | "connectionCheckOutFailed"
          | "connectionCheckedOut"
          | "connectionCheckedIn"
          | "commandStarted"
          | "commandSucceeded"
          | "commandFailed"
          | "serverHeartbeatStarted"
          | "serverHeartbeatSucceeded"
          | "serverHeartbeatFailed"

    Parameters

    Returns MongoClientEvents[EventKey][]

    v9.4.0

  • 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的引用,以便可以链接调用。

    Type Parameters

    • EventKey extends
          | "error"
          | "timeout"
          | "close"
          | "open"
          | "serverOpening"
          | "serverClosed"
          | "serverDescriptionChanged"
          | "topologyOpening"
          | "topologyClosed"
          | "topologyDescriptionChanged"
          | "connectionPoolCreated"
          | "connectionPoolClosed"
          | "connectionPoolCleared"
          | "connectionPoolReady"
          | "connectionCreated"
          | "connectionReady"
          | "connectionClosed"
          | "connectionCheckOutStarted"
          | "connectionCheckOutFailed"
          | "connectionCheckedOut"
          | "connectionCheckedIn"
          | "commandStarted"
          | "commandSucceeded"
          | "commandFailed"
          | "serverHeartbeatStarted"
          | "serverHeartbeatSucceeded"
          | "serverHeartbeatFailed"

    Parameters

    • Optionalevent: string | symbol | EventKey

    Returns this

    v0.1.26

  • 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.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的引用,以便可以链接调用。

    Type Parameters

    • EventKey extends
          | "error"
          | "timeout"
          | "close"
          | "open"
          | "serverOpening"
          | "serverClosed"
          | "serverDescriptionChanged"
          | "topologyOpening"
          | "topologyClosed"
          | "topologyDescriptionChanged"
          | "connectionPoolCreated"
          | "connectionPoolClosed"
          | "connectionPoolCleared"
          | "connectionPoolReady"
          | "connectionCreated"
          | "connectionReady"
          | "connectionClosed"
          | "connectionCheckOutStarted"
          | "connectionCheckOutFailed"
          | "connectionCheckedOut"
          | "connectionCheckedIn"
          | "commandStarted"
          | "commandSucceeded"
          | "commandFailed"
          | "serverHeartbeatStarted"
          | "serverHeartbeatSucceeded"
          | "serverHeartbeatFailed"

    Parameters

    Returns this

    v0.1.26

  • 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的引用,以便可以链接调用。

    Parameters

    Returns this

    v0.1.26

  • 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的引用,以便可以链接调用。

    Parameters

    Returns this

    v0.1.26

  • By default EventEmitters will print a warning if more than 10 listeners are added for a particular event. 默认情况下,如果为特定事件添加了10个以上的监听器,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的引用,以便可以链接调用。

    Parameters

    • n: number

    Returns this

    v0.3.5

  • Creates a new ClientSession. When using the returned session in an operation a corresponding ServerSession will be created.创建新的ClientSession。在操作中使用返回的会话时,将创建相应的ServerSession。

    Parameters

    Returns ClientSession

    A ClientSession instance may only be passed to operations being performed on the same MongoClient it was started from.ClientSession实例只能传递给在启动它的同一MongoClient上执行的操作。

  • Create 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 Parameters

    • TSchema extends Document = Document

      Type of the data being detected by the change stream更改流检测到的数据类型

    • TChange extends Document = ChangeStreamDocument<TSchema>

      Type of the whole change stream document emitted发出的整个变更流文档的类型

    Parameters

    • pipeline: Document[] = []

      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)和操纵更改流文档。

    • options: ChangeStreamOptions = {}

      Optional settings for the command命令的可选设置

    Returns ChangeStream<TSchema, TChange>

    watch() accepts two generic arguments for distinct use cases:watch()为不同的用例接受两个泛型参数:

    • The first is to provide the schema that may be defined for all the data within the current cluster第一个是提供可以为当前集群内的所有数据定义的模式
    • The second is to override the shape of the change stream document entirely, if it is not provided the type will default to ChangeStreamDocument of the first argument第二种方法是完全覆盖更改流文档的形状,如果没有提供,则类型将默认为第一个参数的ChangeStreamDocument

    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清理的便利方法。当执行者完成时,会话将始终结束。

    Type Parameters

    • T = any

    Parameters

    • executor: WithSessionCallback<T>

      An executor function that all operations using the provided session must be invoked in一个执行器函数,必须在其中调用使用所提供会话的所有操作

    Returns Promise<T>

  • Type Parameters

    • T = any

    Parameters

    Returns Promise<T>

  • Listens 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 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.这个API允许在Node.js API中安全地使用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]();
    }
    }

    Parameters

    • signal: AbortSignal
    • resource: ((event: Event) => void)
        • (event): void
        • Parameters

          • event: Event

          Returns void

    Returns Disposable

    Disposable that removes the abort listener.删除abort侦听器的disposable。

    v20.5.0

  • Creates a new MongoClient instance and immediately connects it to MongoDB. This convenience method combines new MongoClient(url, options) and client.connect() in a single step.创建一个新的MongoClient实例,并立即将其连接到MongoDB。这种方便的方法将new MongoClient(url, options)client.connect()组合在一个步骤中。

    Connect can be helpful to detect configuration issues early by validating:Connect可以通过验证以下内容来帮助及早检测配置问题:

    • DNS ResolutionDNS解析: Verifies that SRV records and hostnames in the connection string resolve DNS entries:验证连接字符串中的SRV记录和主机名是否解析DNS条目
    • Network Connectivity网络连接: Confirms that host addresses are reachable and ports are open:确认主机地址可访问且端口已打开
    • TLS ConfigurationTLS配置: Validates SSL/TLS certificates, CA files, and encryption settings are correct:验证SSL/TLS证书、CA文件和加密设置是否正确
    • Authentication认证: Verifies that provided credentials are valid:验证提供的凭据是否有效
    • Server Compatibility服务器兼容性: Ensures the MongoDB server version is supported by this driver version:确保此驱动程序版本支持MongoDB服务器版本
    • Load Balancer Setup负载平衡器设置: For load-balanced deployments, confirms the service is properly configured:对于负载平衡部署,确认服务配置正确

    Parameters

    Returns Promise<MongoClient>

    A 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是可选的,因为如果客户端尚未连接,任何操作方法(findinsertOne等)都会自动执行这些相同的验证步骤。但是,显式调用connect可能对以下情况有意义:

    • Fail-fast Error Detection故障快速错误检测: Non-transient connection issues (hostname unresolved, port refused connection) are discovered immediately rather than during your first operation:非暂时性连接问题(主机名未解析、端口拒绝连接)会立即发现,而不是在第一次操作中发现
    • Predictable Performance系统性能: Eliminates first connection overhead from your first database operation:消除了首次数据库操作的首次连接开销

    /v8.3/reference/connection-string/

  • Returns 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] ]
    }

    Parameters

    • emitter: EventEmitter<DefaultEventMap> | EventTarget
    • name: string | symbol

    Returns Function[]

    v15.2.0, v14.17.0

  • Returns 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
    }

    Parameters

    • emitter: EventEmitter<DefaultEventMap> | EventTarget

    Returns number

    v19.9.0

  • A 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

    Parameters

    • emitter: EventEmitter<DefaultEventMap>

      The emitter to query要查询的发射器

    • eventName: string | symbol

      The event name事件名称

    Returns number

    v0.9.12

    Since v3.2.0 - Use listenerCount instead.

  • 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);
    });

    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事件的AsyncIteratorIt 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'

    Parameters

    • emitter: EventEmitter<DefaultEventMap>
    • eventName: string | symbol
    • Optionaloptions: StaticEventEmitterIteratorOptions

    Returns AsyncIterator<any[], any, any>

    An AsyncIterator that iterates eventName events emitted by the emitter迭代发射器发出的eventName事件的AsyncIterator

    v13.6.0, v12.16.0

  • Parameters

    • emitter: EventTarget
    • eventName: string
    • Optionaloptions: StaticEventEmitterIteratorOptions

    Returns AsyncIterator<any[], any, any>

  • Creates 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'error' event semantics and does not listen to the 'error' event.此方法有意通用,适用于web平台EventTarget接口,该接口没有特殊的'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!打印:等待活动已取消!

    Parameters

    • emitter: EventEmitter<DefaultEventMap>
    • eventName: string | symbol
    • Optionaloptions: StaticEventEmitterOptions

    Returns Promise<any[]>

    v11.13.0, v10.16.0

  • Parameters

    • emitter: EventTarget
    • eventName: string
    • Optionaloptions: StaticEventEmitterOptions

    Returns Promise<any[]>

  • import { setMaxListeners, EventEmitter } from 'node:events';

    const target = new EventTarget();
    const emitter = new EventEmitter();

    setMaxListeners(5, target, emitter);

    Parameters

    • 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}对象的默认最大值。

    Returns void

    v15.4.0