interface ClientSession {
    authenticationToken?: NodeId;
    endpoint: EndpointDescription;
    getTransportSettings?: (() => IBasicTransportSettings);
    isReconnecting: boolean;
    lastRequestSentTime: Date;
    lastResponseReceivedTime: Date;
    name: string;
    requestedMaxReferencesPerNode: number;
    serverCertificate: Buffer;
    serverEndpoints: EndpointDescription[];
    sessionId: NodeId;
    subscriptionCount: number;
    timeout: number;
    [captureRejectionSymbol]?<K>(error: Error, event: string | symbol, ...args: AnyRest): void;
    acknowledgeCondition(conditionId: NodeId, eventId: Buffer, comment: LocalizedTextLike, callback: Callback<StatusCode>): void;
    acknowledgeCondition(conditionId: NodeId, eventId: Buffer, comment: LocalizedTextLike): Promise<StatusCode>;
    addCommentCondition(conditionId: NodeIdLike, eventId: Buffer, comment: LocalizedTextLike, callback: Callback<StatusCode>): void;
    addCommentCondition(conditionId: NodeIdLike, eventId: Buffer, comment: LocalizedTextLike): Promise<StatusCode>;
    addListener<K>(eventName: string | symbol, listener: ((...args: any[]) => void)): this;
    browse(nodeToBrowse: BrowseDescriptionLike): Promise<BrowseResult>;
    browse(nodesToBrowse: BrowseDescriptionLike[]): Promise<BrowseResult[]>;
    browse(nodeToBrowse: BrowseDescriptionLike, callback: ResponseCallback<BrowseResult>): void;
    browse(nodesToBrowse: BrowseDescriptionLike[], callback: ResponseCallback<BrowseResult[]>): void;
    browseNext(continuationPoint: Buffer, releaseContinuationPoints: boolean): Promise<BrowseResult>;
    browseNext(continuationPoints: Buffer[], releaseContinuationPoints: boolean): Promise<BrowseResult[]>;
    browseNext(continuationPoint: Buffer, releaseContinuationPoints: boolean, callback: ResponseCallback<BrowseResult>): void;
    browseNext(continuationPoints: Buffer[], releaseContinuationPoints: boolean, callback: ResponseCallback<BrowseResult[]>): void;
    call(methodToCall: CallMethodRequestOptions): Promise<CallMethodResult>;
    call(methodsToCall: CallMethodRequestOptions[]): Promise<CallMethodResult[]>;
    call(methodToCall: CallMethodRequestOptions, callback: ((err: null | Error, result?: CallMethodResult) => void)): void;
    call(methodsToCall: CallMethodRequestOptions[], callback: ((err: null | Error, results?: CallMethodResult[]) => void)): void;
    changeUser(userIdentityInfo: UserIdentityInfo): Promise<StatusCode>;
    changeUser(userIdentityInfo: UserIdentityInfo, callback: CallbackT<StatusCode>): void;
    close(callback: ErrorCallback): void;
    close(deleteSubscription: boolean, callback: ErrorCallback): void;
    close(deleteSubscription?: boolean): Promise<void>;
    confirmCondition(conditionId: NodeIdLike, eventId: Buffer, comment: LocalizedTextLike, callback: Callback<StatusCode>): void;
    confirmCondition(conditionId: NodeIdLike, eventId: Buffer, comment: LocalizedTextLike): Promise<StatusCode>;
    constructExtensionObject(dataType: NodeId, pojo: Record<string, unknown>): Promise<ExtensionObject>;
    createSubscription2(createSubscriptionRequest: CreateSubscriptionRequestOptions): Promise<ClientSubscription>;
    createSubscription2(createSubscriptionRequest: CreateSubscriptionRequestOptions, callback: ResponseCallback<ClientSubscription>): void;
    disableCondition(): void;
    emit<K>(eventName: string | symbol, ...args: AnyRest): boolean;
    enableCondition(): void;
    eventNames(): (string | symbol)[];
    extractNamespaceDataType(): Promise<ExtraDataTypeManager>;
    findMethodId(nodeId: NodeIdLike, methodName: string, callback: ResponseCallback<NodeId>): void;
    findMethodId(nodeId: NodeIdLike, methodName: string): Promise<NodeId>;
    getArgumentDefinition(methodId: NodeIdLike): Promise<ArgumentDefinition>;
    getArgumentDefinition(methodId: NodeIdLike, callback: ((err: null | Error, args?: ArgumentDefinition) => void)): void;
    getBuiltInDataType(nodeId: NodeId): Promise<DataType>;
    getBuiltInDataType(nodeId: NodeId, callback: ((err: null | Error, dataType?: DataType) => void)): void;
    getMaxListeners(): number;
    getNamespaceIndex(namespaceUri: string): number;
    historyRead(request: HistoryReadRequest, callback: Callback<HistoryReadResponse>): void;
    historyRead(request: HistoryReadRequest): Promise<HistoryReadResponse>;
    listenerCount<K>(eventName: string | symbol, listener?: Function): number;
    listeners<K>(eventName: string | symbol): Function[];
    off<K>(eventName: string | symbol, listener: ((...args: any[]) => void)): this;
    on(event: "keepalive", eventHandler: ((lastKnownServerState: ServerState) => void)): this;
    on(event: "keepalive_failure", eventHandler: ((state: any) => void)): this;
    on(event: "session_closed", eventHandler: ((statusCode: StatusCode) => void)): this;
    on(event: "session_restored", eventHandler: (() => void)): this;
    on(event: string | symbol, listener: ((...args: any[]) => void)): this;
    once<K>(eventName: string | symbol, listener: ((...args: any[]) => void)): this;
    prependListener<K>(eventName: string | symbol, listener: ((...args: any[]) => void)): this;
    prependOnceListener<K>(eventName: string | symbol, listener: ((...args: any[]) => void)): this;
    queryFirst(queryFirstRequest: QueryFirstRequestOptions): Promise<QueryFirstResponse>;
    queryFirst(queryFirstRequest: QueryFirstRequestOptions, callback: ResponseCallback<QueryFirstResponse>): void;
    rawListeners<K>(eventName: string | symbol): Function[];
    read(nodeToRead: ReadValueIdOptions, maxAge?: number): Promise<DataValue>;
    read(nodesToRead: ReadValueIdOptions[], maxAge?: number): Promise<DataValue[]>;
    read(nodeToRead: ReadValueIdOptions, maxAge: number, callback: ResponseCallback<DataValue>): void;
    read(nodesToRead: ReadValueIdOptions[], maxAge: number, callback: ResponseCallback<DataValue[]>): void;
    read(nodeToRead: ReadValueIdOptions, callback: ResponseCallback<DataValue>): void;
    read(nodesToRead: ReadValueIdOptions[], callback: ResponseCallback<DataValue[]>): void;
    readAggregateValue(nodesToRead: HistoryReadValueIdOptions[], startTime: DateTime, endTime: DateTime, aggregateFn: AggregateFunction[], processingInterval: number, callback: Callback<HistoryReadResult[]>): void;
    readAggregateValue(nodesToRead: HistoryReadValueIdOptions[], startTime: DateTime, endTime: DateTime, aggregateFn: AggregateFunction[], processingInterval: number): Promise<HistoryReadResult[]>;
    readAggregateValue(nodeToRead: HistoryReadValueIdOptions, startTime: DateTime, endTime: DateTime, aggregateFn: AggregateFunction, processingInterval: number, callback: Callback<HistoryReadResult>): void;
    readAggregateValue(nodeToRead: HistoryReadValueIdOptions, startTime: DateTime, endTime: DateTime, aggregateFn: AggregateFunction, processingInterval: number): Promise<HistoryReadResult>;
    readAggregateValue(nodesToRead: HistoryReadValueIdOptions[], startTime: DateTime, endTime: DateTime, aggregateFn: AggregateFunction[], processingInterval: number, aggregateConfiguration: AggregateConfigurationOptions, callback: Callback<HistoryReadResult[]>): void;
    readAggregateValue(nodesToRead: HistoryReadValueIdOptions[], startTime: DateTime, endTime: DateTime, aggregateFn: AggregateFunction[], processingInterval: number, aggregateConfiguration: AggregateConfigurationOptions): Promise<HistoryReadResult[]>;
    readAggregateValue(nodeToRead: HistoryReadValueIdOptions, startTime: DateTime, endTime: DateTime, aggregateFn: AggregateFunction, processingInterval: number, aggregateConfiguration: AggregateConfigurationOptions, callback: Callback<HistoryReadResult>): void;
    readAggregateValue(nodeToRead: HistoryReadValueIdOptions, startTime: DateTime, endTime: DateTime, aggregateFn: AggregateFunction, processingInterval: number, aggregateConfiguration: AggregateConfigurationOptions): Promise<HistoryReadResult>;
    readHistoryValue(nodesToRead: NodeIdLike[] | HistoryReadValueIdOptions2[], start: DateTime, end: DateTime, callback: ((err: null | Error, results?: HistoryReadResult[]) => void)): void;
    readHistoryValue(nodesToRead: NodeIdLike[] | HistoryReadValueIdOptions2[], start: DateTime, end: DateTime, options: undefined | ExtraReadHistoryValueParameters, callback: ((err: null | Error, results?: HistoryReadResult[]) => void)): void;
    readHistoryValue(nodesToRead: NodeIdLike[] | HistoryReadValueIdOptions2[], start: DateTime, end: DateTime, options?: ExtraReadHistoryValueParameters): Promise<HistoryReadResult[]>;
    readHistoryValue(nodeToRead: NodeIdLike | HistoryReadValueIdOptions2, start: DateTime, end: DateTime, callback: ((err: null | Error, result?: HistoryReadResult) => void)): void;
    readHistoryValue(nodeToRead: NodeIdLike | HistoryReadValueIdOptions2, start: DateTime, end: DateTime, options: undefined | ExtraReadHistoryValueParameters, callback: ((err: null | Error, result?: HistoryReadResult) => void)): void;
    readHistoryValue(nodeToRead: NodeIdLike | HistoryReadValueIdOptions2, start: DateTime, end: DateTime, options?: ExtraReadHistoryValueParameters): Promise<HistoryReadResult>;
    readNamespaceArray(): Promise<string[]>;
    readNamespaceArray(callback: ((err: null | Error, namespaceArray?: string[]) => void)): void;
    readVariableValue(nodeId: NodeIdLike, callback: ResponseCallback<DataValue>): void;
    readVariableValue(nodeId: NodeIdLike): Promise<DataValue>;
    readVariableValue(nodeIds: NodeIdLike[], callback: ResponseCallback<DataValue[]>): void;
    readVariableValue(nodeIds: NodeIdLike[]): Promise<DataValue[]>;
    registerNodes(nodesToRegister: NodeIdLike[]): Promise<NodeId[]>;
    registerNodes(nodesToRegister: NodeIdLike[], callback: ((err: null | Error, registeredNodeIds?: NodeId[]) => void)): void;
    removeAllListeners(eventName?: string | symbol): this;
    removeListener<K>(eventName: string | symbol, listener: ((...args: any[]) => void)): this;
    setMaxListeners(n: number): this;
    translateBrowsePath(browsePath: BrowsePath): Promise<BrowsePathResult>;
    translateBrowsePath(browsePaths: BrowsePath[]): Promise<BrowsePathResult[]>;
    translateBrowsePath(browsesPath: BrowsePath[], callback: ResponseCallback<BrowsePathResult[]>): void;
    translateBrowsePath(browsePath: BrowsePath, callback: ResponseCallback<BrowsePathResult>): void;
    unregisterNodes(nodesToRegister: NodeIdLike[]): Promise<void>;
    unregisterNodes(nodesToRegister: NodeIdLike[], callback: ((err?: Error) => void)): void;
    write(nodeToWrite: WriteValueOptions): Promise<StatusCode>;
    write(nodesToWrite: WriteValueOptions[]): Promise<StatusCode[]>;
    write(nodeToWrite: WriteValueOptions, callback: ResponseCallback<StatusCode>): void;
    write(nodesToWrite: WriteValueOptions[], callback: ResponseCallback<StatusCode[]>): void;
}

Hierarchy (view full)

Properties

authenticationToken?: NodeId
getTransportSettings?: (() => IBasicTransportSettings)
isReconnecting: boolean
lastRequestSentTime: Date

the time of the latest request sent by the client to the server

lastResponseReceivedTime: Date

the time of the latest response received by the client

name: string

the session name

requestedMaxReferencesPerNode: number

the maximum number of reference that the server should return per browseResult Continuous points will be return by server to allow retrieving remaining references with browseNext

serverCertificate: Buffer

the server certificate as provided by the server

serverEndpoints: EndpointDescription[]
sessionId: NodeId
subscriptionCount: number
timeout: number

the session Id

Methods

  • Type Parameters

    • K

    Parameters

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

    Returns void

  • helper to acknowledge a condition

    from Spec 1.03 Part 9 : page 27

    The Acknowledge Method is used to acknowledge an Event Notification for a Condition instance state where AckedState is false.

    Normally, the NodeId of the object instance as the ObjectId is passed to the Call Service.

    However, some Servers do not expose Condition instances in the AddressSpace.

    Therefore all Servers shall also allow Clients to call the Acknowledge Method by specifying ConditionId as the ObjectId.

    The Method cannot be called with an ObjectId of the AcknowledgeableConditionType Node.

    A Condition instance may be an Object that appears in the Server Address Space. If this is the case the ConditionId is the NodeId for the Object.

    The EventId identifies a specific Event Notification where a state to be acknowledged was reported.

    Acknowledgement and the optional comment will be applied to the state identified with the EventId. If the comment field is NULL (both locale and text are empty) it will be ignored and any existing comments will remain unchanged. If the comment is to be reset, an empty text with a locale shall be provided.

    A valid EventId will result in an Event Notification where AckedState/Id is set to TRUE and the Comment Property contains the text of the optional comment argument. If a previous state is acknowledged, the BranchId and all Condition values of this branch will be reported.

    Parameters

    Returns void

  • Parameters

    Returns Promise<StatusCode>

  • helper to add a comment to a condition

    The addComment Method is used to apply a comment to a specific state of a Condition instance.

    Normally, the NodeId of the object instance as the ObjectId is passed to the Call Service.

    However, some Servers do not expose Condition instances in the AddressSpace. Therefore all Servers shall also allow Clients to call the AddComment Method by specifying ConditionId as the ObjectId.

    The Method cannot be called with an ObjectId of the ConditionType Node.

    • Comments are added to Event occurrences identified via an EventId. EventIds where the related EventType is not a ConditionType (or subtype of it) and thus does not support Comments are rejected.
    • A ConditionEvent – where the Comment Variable contains this text – will be sent for the identified state. If a comment is added to a previous state (i.e. a state for which the Server has created a branch), the BranchId and all Condition values of this branch will be reported/.

    Parameters

    Returns void

  • Parameters

    Returns Promise<StatusCode>

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

    Type Parameters

    • K

    Parameters

    • eventName: string | symbol
    • listener: ((...args: any[]) => void)
        • (...args): void
        • Parameters

          • Rest...args: any[]

          Returns void

    Returns this

    v0.1.26

  • Parameters

    • continuationPoint: Buffer
    • releaseContinuationPoints: boolean

      a Boolean parameter with the following values: * true passed continuationPoints shall be reset to free resources in the Server. The continuation points are released and the results and diagnosticInfos arrays are empty. * false passed continuationPoints shall be used to get the next set of browse information.

      A Client shall always use the continuation point returned by a Browse or BrowseNext response to free the resources for the continuation point in the Server. If the Client does not want to get the next set of browse information, BrowseNext shall be called with this parameter set to true.

    Returns Promise<BrowseResult>

  • Parameters

    • continuationPoints: Buffer[]
    • releaseContinuationPoints: boolean

    Returns Promise<BrowseResult[]>

  • Parameters

    Returns void

  • Parameters

    Returns void

  • Parameters

    Returns Promise<CallMethodResult>

    const methodToCall = {
    objectId: "ns=2;i=12",
    methodId: "ns=2;i=13",
    inputArguments: [
    new Variant({...}),
    new Variant({...}),
    ]
    }
    session.call(methodToCall,function(err,callResult) {
    if (!err) {
    console.log(" statusCode = ",callResult.statusCode);
    console.log(" inputArgumentResults[0] = ",callResult.inputArgumentResults[0].toString());
    console.log(" inputArgumentResults[1] = ",callResult.inputArgumentResults[1].toString());
    console.log(" outputArgument[0] = ",callResult.outputArgument[0].toString()); // array of variant
    }
    });
    const methodsToCall = [ {
    objectId: "ns=2;i=12",
    methodId: "ns=2;i=13",
    inputArguments: [
    new Variant({...}),
    new Variant({...}),
    ]
    }];
    session.call(methodsToCall,function(err,callResults) {
    if (!err) {
    const callResult = callResults[0];
    console.log(" statusCode = ",rep.statusCode);
    console.log(" inputArgumentResults[0] = ",callResult.inputArgumentResults[0].toString());
    console.log(" inputArgumentResults[1] = ",callResult.inputArgumentResults[1].toString());
    console.log(" outputArgument[0] = ",callResult.outputArgument[0].toString()); // array of variant
    }
    });
  • Parameters

    Returns Promise<CallMethodResult[]>

  • Parameters

    Returns void

  • Parameters

    Returns void

  • Synchronously calls each of the listeners registered for the event named eventName, in the order they were registered, passing the supplied arguments to each.

    Returns true if the event had listeners, false otherwise.

    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

    Type Parameters

    • K

    Parameters

    • eventName: string | symbol
    • Rest...args: AnyRest

    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.

    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 | symbol)[]

    v6.0.0

  • Returns the current max listener value for the EventEmitter which is either set by emitter.setMaxListeners(n) or defaults to 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.

    Type Parameters

    • K

    Parameters

    • eventName: string | symbol

      The name of the event being listened for

    • Optionallistener: Function

      The event handler function

    Returns number

    v3.2.0

  • Returns a copy of the array of listeners for the event named eventName.

    server.on('connection', (stream) => {
    console.log('someone connected!');
    });
    console.log(util.inspect(server.listeners('connection')));
    // Prints: [ [Function] ]

    Type Parameters

    • K

    Parameters

    • eventName: string | symbol

    Returns Function[]

    v0.1.26

  • Alias for emitter.removeListener().

    Type Parameters

    • K

    Parameters

    • eventName: string | symbol
    • listener: ((...args: any[]) => void)
        • (...args): void
        • Parameters

          • Rest...args: any[]

          Returns void

    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.

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

    Returns a reference to the EventEmitter, so that calls can be chained.

    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.

    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: "keepalive"
    • eventHandler: ((lastKnownServerState: ServerState) => void)
        • (lastKnownServerState): 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. 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.

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

    Returns a reference to the EventEmitter, so that calls can be chained.

    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.

    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: "keepalive_failure"
    • eventHandler: ((state: any) => void)
        • (state): void
        • Parameters

          • state: any

          Returns void

    Returns this

    v0.1.101

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

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

    Returns a reference to the EventEmitter, so that calls can be chained.

    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.

    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: "session_closed"
    • eventHandler: ((statusCode: StatusCode) => void)
        • (statusCode): void
        • Parameters

          Returns void

    Returns this

    v0.1.101

  • session_restored is raised when the session and related subscription have been fully repaired after a reconnection.

    Parameters

    • event: "session_restored"
    • eventHandler: (() => void)
        • (): void
        • Returns void

    Returns this

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

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

    Returns a reference to the EventEmitter, so that calls can be chained.

    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.

    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: string | symbol
    • listener: ((...args: any[]) => void)

      The callback function

        • (...args): void
        • Parameters

          • Rest...args: any[]

          Returns void

    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.

    server.once('connection', (stream) => {
    console.log('Ah, we have our first user!');
    });

    Returns a reference to the EventEmitter, so that calls can be chained.

    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.

    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

    • K

    Parameters

    • eventName: string | symbol

      The name of the event.

    • listener: ((...args: any[]) => void)

      The callback function

        • (...args): void
        • Parameters

          • Rest...args: any[]

          Returns void

    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.

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

    Returns a reference to the EventEmitter, so that calls can be chained.

    Type Parameters

    • K

    Parameters

    • eventName: string | symbol

      The name of the event.

    • listener: ((...args: any[]) => void)

      The callback function

        • (...args): void
        • Parameters

          • Rest...args: any[]

          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.

    server.prependOnceListener('connection', (stream) => {
    console.log('Ah, we have our first user!');
    });

    Returns a reference to the EventEmitter, so that calls can be chained.

    Type Parameters

    • K

    Parameters

    • eventName: string | symbol

      The name of the event.

    • listener: ((...args: any[]) => void)

      The callback function

        • (...args): void
        • Parameters

          • Rest...args: any[]

          Returns void

    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()).

    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
    const listeners = emitter.rawListeners('log');
    const logFnWrapper = listeners[0];

    // Logs "log once" to the console and does not unbind the `once` event
    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
    const newListeners = emitter.rawListeners('log');

    // Logs "log persistently" twice
    newListeners[0]();
    emitter.emit('log');

    Type Parameters

    • K

    Parameters

    • eventName: string | symbol

    Returns Function[]

    v9.4.0

  • Removes all listeners, or those of the specified 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).

    Returns a reference to the EventEmitter, so that calls can be chained.

    Parameters

    • OptionaleventName: string | symbol

    Returns this

    v0.1.26

  • Removes the specified listener from the listener array for the event named eventName.

    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.

    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.

    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.

    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:

    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.

    Type Parameters

    • K

    Parameters

    • eventName: string | symbol
    • listener: ((...args: any[]) => void)
        • (...args): void
        • Parameters

          • Rest...args: any[]

          Returns void

    Returns this

    v0.1.26

  • By default EventEmitters will print a warning if more than 10 listeners are added for a particular event. 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.

    Returns a reference to the EventEmitter, so that calls can be chained.

    Parameters

    • n: number

    Returns this

    v0.3.5