DigitalWorldEvent
Defined in: src/models/event.ts:255
Typed Event Emitter class which can act as a Base Model for all our model and communication events. This makes it much easier for us to distinguish between events, as we now need to properly type this, so that our events are not stringly-based and prone to silly typos.
Type parameters:
Events- List of all events emitted by thisTypedEventEmitter. Normally an enum type.Arguments- A ListenerMap type providing mappings from event names to listener types.SuperclassArguments- TODO: not really sure. Alternative listener mappings, I think? But only honoured for.emit?
Extends
Section titled “Extends”Constructors
Section titled “Constructors”Constructor
Section titled “Constructor”new DigitalWorldEvent(
event?):DigitalWorldEvent
Defined in: src/models/event.ts:430
Construct a Digital World Event object
Parameters
Section titled “Parameters”event?
Section titled “event?”Partial<IEvent> = {}
The raw (possibly encrypted) event. Do not access this property directly unless you absolutely have to. Prefer the getter methods defined on this class. Using the getter methods shields your app from changes to event JSON between protocol versions.
Returns
Section titled “Returns”DigitalWorldEvent
Overrides
Section titled “Overrides”Properties
Section titled “Properties”error:
DigitalWorldError|null=null
Defined in: src/models/event.ts:398
most recent error associated with sending the event, if any
event:
Partial<IEvent> ={}
Defined in: src/models/event.ts:430
The raw (possibly encrypted) event. Do not access this property directly unless you absolutely have to. Prefer the getter methods defined on this class. Using the getter methods shields your app from changes to event JSON between protocol versions.
forwardLooking
Section titled “forwardLooking”forwardLooking:
boolean=true
Defined in: src/models/event.ts:407
True if this event is ‘forward looking’, meaning that getDirectionalContent() will return event.content and not event.prev_content. Only state events may be backwards looking Default: true. This property is experimental and may change.
localTimestamp
Section titled “localTimestamp”localTimestamp:
number
Defined in: src/models/event.ts:323
sender
Section titled “sender”sender:
RoomMember|null=null
Defined in: src/models/event.ts:333
The room member who sent this event, or null e.g. this is a presence event. This is only guaranteed to be set for events that appear in a timeline, ie. do not guarantee that it will be set on state events.
status
Section titled “status”status:
EventStatus|null=null
Defined in: src/models/event.ts:392
The sending status of the event.
target
Section titled “target”target:
RoomMember|null=null
Defined in: src/models/event.ts:341
The room member who is the target of this event, e.g. the invitee, the person being banned, etc.
unstableStickyExpiresAt
Section titled “unstableStickyExpiresAt”
readonlyunstableStickyExpiresAt:number|undefined
Defined in: src/models/event.ts:420
The timestamp for when this event should expire, in milliseconds. Prefers using the server-provided value, but will fall back to local calculation.
This value is safe to use, as malicious start time and duration are appropriately capped.
If the event is not a sticky event (or not supported by the server),
then this returns undefined.
captureRejections
Section titled “captureRejections”
staticcaptureRejections:boolean
Defined in: node_modules/.pnpm/@types+node@22.20.0/node_modules/@types/node/events.d.ts:425
Value: boolean
Change the default captureRejections option on all new EventEmitter objects.
v13.4.0, v12.16.0
Inherited from
Section titled “Inherited from”TypedEventEmitter.captureRejections
captureRejectionSymbol
Section titled “captureRejectionSymbol”
readonlystaticcaptureRejectionSymbol: typeofcaptureRejectionSymbol
Defined in: node_modules/.pnpm/@types+node@22.20.0/node_modules/@types/node/events.d.ts:418
Value: Symbol.for('nodejs.rejection')
See how to write a custom rejection handler.
v13.4.0, v12.16.0
Inherited from
Section titled “Inherited from”TypedEventEmitter.captureRejectionSymbol
defaultMaxListeners
Section titled “defaultMaxListeners”
staticdefaultMaxListeners:number
Defined in: node_modules/.pnpm/@types+node@22.20.0/node_modules/@types/node/events.d.ts:464
By default, a maximum of 10 listeners can be registered for any single
event. This limit can be changed for individual EventEmitter instances
using the emitter.setMaxListeners(n) method. To change the default
for allEventEmitter instances, the events.defaultMaxListeners property
can be used. If this value is not a positive number, a RangeError is thrown.
Take caution when setting the events.defaultMaxListeners because the
change affects all EventEmitter instances, including those created before
the change is made. However, calling emitter.setMaxListeners(n) still has
precedence over 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. For any single
EventEmitter, the emitter.getMaxListeners() and emitter.setMaxListeners() methods can be used to
temporarily avoid this warning:
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.
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.
Its name property is set to 'MaxListenersExceededWarning'.
v0.11.2
Inherited from
Section titled “Inherited from”TypedEventEmitter.defaultMaxListeners
errorMonitor
Section titled “errorMonitor”
readonlystaticerrorMonitor: typeoferrorMonitor
Defined in: node_modules/.pnpm/@types+node@22.20.0/node_modules/@types/node/events.d.ts:411
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.
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.
v13.6.0, v12.17.0
Inherited from
Section titled “Inherited from”TypedEventEmitter.errorMonitor
Accessors
Section titled “Accessors”decryptionFailureReason
Section titled “decryptionFailureReason”Get Signature
Section titled “Get Signature”get decryptionFailureReason():
DecryptionFailureCode|null
Defined in: src/models/event.ts:862
If we failed to decrypt this event, the reason for the failure. Otherwise, null.
Returns
Section titled “Returns”DecryptionFailureCode | null
isThreadRoot
Section titled “isThreadRoot”Get Signature
Section titled “Get Signature”get isThreadRoot():
boolean
Defined in: src/models/event.ts:685
A helper to check if an event is a thread’s head or not
Returns
Section titled “Returns”boolean
relationEventId
Section titled “relationEventId”Get Signature
Section titled “Get Signature”get relationEventId():
string|undefined
Defined in: src/models/event.ts:703
Returns
Section titled “Returns”string | undefined
replyEventId
Section titled “replyEventId”Get Signature
Section titled “Get Signature”get replyEventId():
string|undefined
Defined in: src/models/event.ts:699
Returns
Section titled “Returns”string | undefined
threadRootId
Section titled “threadRootId”Get Signature
Section titled “Get Signature”get threadRootId():
string|undefined
Defined in: src/models/event.ts:660
Get the event ID of the thread head
Returns
Section titled “Returns”string | undefined
unstableExtensibleEvent
Section titled “unstableExtensibleEvent”Get Signature
Section titled “Get Signature”get unstableExtensibleEvent():
ExtensibleEvent<object> |undefined
Defined in: src/models/event.ts:481
Unstable getter to try and get an extensible event. Note that this might return a falsy value if the event could not be parsed as an extensible event.
Returns
Section titled “Returns”ExtensibleEvent<object> | undefined
unstableStickyInfo
Section titled “unstableStickyInfo”Get Signature
Section titled “Get Signature”get unstableStickyInfo(): {
duration_ms:number;duration_ttl_ms?:number; } |undefined
Defined in: src/models/event.ts:1771
Unstable getter to try and get the sticky information for the event.
If the event is not a sticky event (or not supported by the server),
then this returns undefined.
duration_ms is safely bounded to a hour.
Returns
Section titled “Returns”{ duration_ms: number; duration_ttl_ms?: number; } | undefined
Methods
Section titled “Methods”[captureRejectionSymbol]()?
Section titled “[captureRejectionSymbol]()?”
optional[captureRejectionSymbol]<K>(error,event, …args):void
Defined in: node_modules/.pnpm/@types+node@22.20.0/node_modules/@types/node/events.d.ts:103
Type Parameters
Section titled “Type Parameters”K
Parameters
Section titled “Parameters”Error
string | symbol
…AnyRest
Returns
Section titled “Returns”void
Inherited from
Section titled “Inherited from”TypedEventEmitter.[captureRejectionSymbol]
addListener()
Section titled “addListener()”addListener<
T>(event,listener):this
Defined in: src/models/typed-event-emitter.ts:70
Alias for on.
Type Parameters
Section titled “Type Parameters”T extends EventEmitterEvents | DigitalWorldEventEmittedEvents
Parameters
Section titled “Parameters”T
listener
Section titled “listener”Listener<DigitalWorldEventEmittedEvents, DigitalWorldEventHandlerMap, T>
Returns
Section titled “Returns”this
Inherited from
Section titled “Inherited from”applyVisibilityEvent()
Section titled “applyVisibilityEvent()”applyVisibilityEvent(
visibilityChange?):void
Defined in: src/models/event.ts:1186
Change the visibility of an event, as per https://github.com/matrix-org/matrix-doc/pull/3531 .
Parameters
Section titled “Parameters”visibilityChange?
Section titled “visibilityChange?”event holding a hide/unhide payload, or nothing if the event is being reset to its original visibility (presumably by a visibility event being redacted).
Returns
Section titled “Returns”void
Remarks
Section titled “Remarks”Fires DigitalWorldEventEvent.VisibilityChange if visibilityEvent
caused a change in the actual visibility of this event, either by making it
visible (if it was hidden), by making it hidden (if it was visible) or by
changing the reason (if it was hidden).
asVisibilityChange()
Section titled “asVisibilityChange()”asVisibilityChange():
IVisibilityChange|null
Defined in: src/models/event.ts:1335
Return the visibility change caused by this event, as per https://github.com/matrix-org/matrix-doc/pull/3531.
Returns
Section titled “Returns”IVisibilityChange | null
If the event is a well-formed visibility change event,
an instance of IVisibilityChange, otherwise null.
emit()
Section titled “emit()”Call Signature
Section titled “Call Signature”emit<
T>(event, …args):boolean
Defined in: src/models/typed-event-emitter.ts:86
Synchronously calls each of the listeners registered for the event named
event, in the order they were registered, passing the supplied arguments
to each.
Type Parameters
Section titled “Type Parameters”T extends DigitalWorldEventEmittedEvents
Parameters
Section titled “Parameters”T
The name of the event to emit
…Parameters<DigitalWorldEventHandlerMap[T]>
Arguments to pass to the listener
Returns
Section titled “Returns”boolean
true if the event had listeners, false otherwise.
Inherited from
Section titled “Inherited from”Call Signature
Section titled “Call Signature”emit<
T>(event, …args):boolean
Defined in: src/models/typed-event-emitter.ts:87
Synchronously calls each of the listeners registered for the event named
event, in the order they were registered, passing the supplied arguments
to each.
Type Parameters
Section titled “Type Parameters”T extends DigitalWorldEventEmittedEvents
Parameters
Section titled “Parameters”T
The name of the event to emit
…Parameters<DigitalWorldEventHandlerMap[T]>
Arguments to pass to the listener
Returns
Section titled “Returns”boolean
true if the event had listeners, false otherwise.
Inherited from
Section titled “Inherited from”emitPromised()
Section titled “emitPromised()”Call Signature
Section titled “Call Signature”emitPromised<
T>(event, …args):Promise<boolean>
Defined in: src/models/typed-event-emitter.ts:98
Similar to emit but calls all listeners within a Promise.all and returns the promise chain
Type Parameters
Section titled “Type Parameters”T extends DigitalWorldEventEmittedEvents
Parameters
Section titled “Parameters”T
The name of the event to emit
…Parameters<DigitalWorldEventHandlerMap[T]>
Arguments to pass to the listener
Returns
Section titled “Returns”Promise<boolean>
true if the event had listeners, false otherwise.
Inherited from
Section titled “Inherited from”TypedEventEmitter.emitPromised
Call Signature
Section titled “Call Signature”emitPromised<
T>(event, …args):Promise<boolean>
Defined in: src/models/typed-event-emitter.ts:102
Similar to emit but calls all listeners within a Promise.all and returns the promise chain
Type Parameters
Section titled “Type Parameters”T extends DigitalWorldEventEmittedEvents
Parameters
Section titled “Parameters”T
The name of the event to emit
…Parameters<DigitalWorldEventHandlerMap[T]>
Arguments to pass to the listener
Returns
Section titled “Returns”Promise<boolean>
true if the event had listeners, false otherwise.
Inherited from
Section titled “Inherited from”TypedEventEmitter.emitPromised
eventNames()
Section titled “eventNames()”eventNames(): (
string|symbol)[]
Defined in: node_modules/.pnpm/@types+node@22.20.0/node_modules/@types/node/events.d.ts:967
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
Section titled “Returns”(string | symbol)[]
v6.0.0
Inherited from
Section titled “Inherited from”flagCancelled()
Section titled “flagCancelled()”flagCancelled(
cancelled?):void
Defined in: src/models/event.ts:1642
Flags an event as cancelled due to future conditions. For example, a verification request event in the same sync transaction may be flagged as cancelled to warn listeners that a cancellation event is coming down the same pipe shortly.
Parameters
Section titled “Parameters”cancelled?
Section titled “cancelled?”boolean = true
Whether the event is to be cancelled or not.
Returns
Section titled “Returns”void
getAge()
Section titled “getAge()”getAge():
number|undefined
Defined in: src/models/event.ts:737
Get the age of this event. This represents the age of the event when the event arrived at the device, and not the age of the event when this function was called. Can only be returned once the server has echo’ed back
Returns
Section titled “Returns”number | undefined
The age of this event in milliseconds.
getAssociatedId()
Section titled “getAssociatedId()”getAssociatedId():
string|undefined
Defined in: src/models/event.ts:1601
For relations and redactions, returns the event_id this event is referring to.
Returns
Section titled “Returns”string | undefined
getAssociatedStatus()
Section titled “getAssociatedStatus()”getAssociatedStatus():
EventStatus|null
Defined in: src/models/event.ts:1541
Returns the status of any associated edit or redaction (not for reactions/annotations as their local echo doesn’t affect the original event), or else the status of the event.
Returns
Section titled “Returns”EventStatus | null
getClaimedEd25519Key()
Section titled “getClaimedEd25519Key()”getClaimedEd25519Key():
string|null
Defined in: src/models/event.ts:1111
Get the ed25519 the sender of this event claims to own.
For Olm messages, this claim is encoded directly in the plaintext of the event itself. For megolm messages, it is implied by the m.room_key event which established the megolm session.
Until we download the device list of the sender, it’s just a claim: the device list gives a proof that the owner of the curve25519 key used for this event (and returned by #getSenderKey) also owns the ed25519 key by signing the public curve25519 key with the ed25519 key.
In general, applications should not use this method directly, but should instead use crypto-api!CryptoApi#getEncryptionInfoForEvent.
Returns
Section titled “Returns”string | null
getClearContent()
Section titled “getClearContent()”getClearContent():
IContent|null
Defined in: src/models/event.ts:1056
Gets the cleartext content for this event. If the event is not encrypted, or encryption has not been completed, this will return null.
Returns
Section titled “Returns”IContent | null
The cleartext (decrypted) content for the event
getContent()
Section titled “getContent()”getContent<
T>():T
Defined in: src/models/event.ts:637
Get the (decrypted, if necessary) event content JSON,
or the content from the replacing event, if any.
See makeReplaced.
Type Parameters
Section titled “Type Parameters”Returns
Section titled “Returns”T
The event content JSON, or an empty object.
getDate()
Section titled “getDate()”getDate():
Date|null
Defined in: src/models/event.ts:587
Get the timestamp of this event, as a Date object.
Returns
Section titled “Returns”Date | null
The event date, e.g. new Date(1433502692297)
getDecryptionPromise()
Section titled “getDecryptionPromise()”getDecryptionPromise():
Promise<void> |null
Defined in: src/models/event.ts:845
Returns
Section titled “Returns”Promise<void> | null
getDetails()
Section titled “getDetails()”getDetails():
string
Defined in: src/models/event.ts:602
Get a string containing details of this event
This is intended for logging, to help trace errors. Example output:
Returns
Section titled “Returns”string
Example
Section titled “Example”id=$HjnOHV646n0SjLDAqFrgIjim7RCpB7cdMXFrekWYAn type=m.room.encryptedsender=@user:example.com room=!room:example.com ts=2022-10-25T17:30:28.404ZgetDirectionalContent()
Section titled “getDirectionalContent()”getDirectionalContent():
IContent
Defined in: src/models/event.ts:726
Get either ‘content’ or ‘prev_content’ depending on if this event is ‘forward-looking’ or not. This can be modified via event.forwardLooking. In practice, this means we get the chronologically earlier content value for this event (this method should surely be called getEarlierContent) This method is experimental and may change.
Returns
Section titled “Returns”event.content if this event is forward-looking, else event.prev_content.
getEffectiveEvent()
Section titled “getEffectiveEvent()”getEffectiveEvent():
IEvent
Defined in: src/models/event.ts:501
Gets the event as it would appear if it had been sent unencrypted.
If the event is encrypted, we attempt to mock up an event as it would have looked had the sender not encrypted it. If the event is not encrypted, a copy of it is simply returned as-is.
Returns
Section titled “Returns”A shallow copy of the event, in wire format, as it would have been had it not been encrypted.
getForwardingCurve25519KeyChain()
Section titled “getForwardingCurve25519KeyChain()”getForwardingCurve25519KeyChain():
string[]
Defined in: src/models/event.ts:1126
Returns an empty array.
Previously, this returned the chain of Curve25519 keys through which
this session was forwarded, via m.forwarded_room_key events.
However, that is not cryptographically reliable, and clients should not
be using it.
Returns
Section titled “Returns”string[]
https://github.com/matrix-org/matrix-spec/issues/1089
getId()
Section titled “getId()”getId():
string|undefined
Defined in: src/models/event.ts:531
Get the event_id for this event.
Returns
Section titled “Returns”string | undefined
The event ID, e.g. $143350589368169JsLZx:localhost
getKeyForwardingUser()
Section titled “getKeyForwardingUser()”getKeyForwardingUser():
string|undefined
Defined in: src/models/event.ts:1142
If another user forwarded the key to this message (eg via MSC4268), get the ID of that user.
Returns
Section titled “Returns”string | undefined
getKeyRequestRecipients()
Section titled “getKeyRequestRecipients()”getKeyRequestRecipients(
userId):IKeyRequestRecipient[]
Defined in: src/models/event.ts:922
Calculate the recipients for keyshare requests.
Parameters
Section titled “Parameters”userId
Section titled “userId”string
the user who received this event.
Returns
Section titled “Returns”IKeyRequestRecipient[]
array of recipients
getKeysClaimed()
Section titled “getKeysClaimed()”getKeysClaimed():
Partial<Record<"ed25519",string>>
Defined in: src/models/event.ts:1088
The additional keys the sender of this encrypted event claims to possess.
Just a wrapper for #getClaimedEd25519Key (q.v.)
Returns
Section titled “Returns”Partial<Record<"ed25519", string>>
getLocalAge()
Section titled “getLocalAge()”getLocalAge():
number
Defined in: src/models/event.ts:747
Get the age of the event when this function was called. This is the ‘age’ field adjusted according to how long this client has had the event.
Returns
Section titled “Returns”number
The age of this event in milliseconds.
getMaxListeners()
Section titled “getMaxListeners()”getMaxListeners():
number
Defined in: node_modules/.pnpm/@types+node@22.20.0/node_modules/@types/node/events.d.ts:819
Returns the current max listener value for the EventEmitter which is either
set by emitter.setMaxListeners(n) or defaults to EventEmitter.defaultMaxListeners.
Returns
Section titled “Returns”number
v1.0.0
Inherited from
Section titled “Inherited from”TypedEventEmitter.getMaxListeners
getMembershipAtEvent()
Section titled “getMembershipAtEvent()”getMembershipAtEvent():
string|undefined
Defined in: src/models/event.ts:789
Get the user’s room membership at the time the event was sent, as reported by the server. This uses MSC4115.
Returns
Section titled “Returns”string | undefined
The user’s room membership, or undefined if the server does
not report it.
getOriginalContent()
Section titled “getOriginalContent()”getOriginalContent<
T>():T
Defined in: src/models/event.ts:620
Get the (decrypted, if necessary) event content JSON, even if the event was replaced by another event.
Type Parameters
Section titled “Type Parameters”T = IContent
Returns
Section titled “Returns”T
The event content JSON, or an empty object.
getPrevContent()
Section titled “getPrevContent()”getPrevContent():
IContent
Defined in: src/models/event.ts:712
Get the previous event content JSON. This will only return something for state events which exist in the timeline.
Returns
Section titled “Returns”The previous event content JSON, or an empty object.
getPushActions()
Section titled “getPushActions()”getPushActions():
IActionsObject|null
Defined in: src/models/event.ts:1399
Get the push actions, if known, for this event
Returns
Section titled “Returns”IActionsObject | null
push actions
getPushDetails()
Section titled “getPushDetails()”getPushDetails():
PushDetails
Defined in: src/models/event.ts:1408
Get the push details, if known, for this event
Returns
Section titled “Returns”push actions
getRedactionEvent()
Section titled “getRedactionEvent()”getRedactionEvent():
EmptyObject|IEvent|null
Defined in: src/models/event.ts:1382
Get the (decrypted, if necessary) redaction event JSON if event was redacted
Returns
Section titled “Returns”EmptyObject | IEvent | null
The redaction event JSON, or an empty object
getRelation()
Section titled “getRelation()”getRelation():
IEventRelation|null
Defined in: src/models/event.ts:1502
Get relation info for the event, if any.
Returns
Section titled “Returns”IEventRelation | null
getRoomId()
Section titled “getRoomId()”getRoomId():
string|undefined
Defined in: src/models/event.ts:571
Get the room_id for this event. This will return undefined
for m.presence events.
Returns
Section titled “Returns”string | undefined
The room ID, e.g. !cURbafjkfsMDVwdRDQ:matrix.org
getSender()
Section titled “getSender()”getSender():
string|undefined
Defined in: src/models/event.ts:539
Get the user_id for this event.
Returns
Section titled “Returns”string | undefined
The user ID, e.g. @alice:matrix.org
getSenderKey()
Section titled “getSenderKey()”getSenderKey():
string|null
Defined in: src/models/event.ts:1079
The curve25519 key for the device that we think sent this event
For an Olm-encrypted event, this is inferred directly from the DH exchange at the start of the session: the curve25519 key is involved in the DH exchange, so only a device which holds the private part of that key can establish such a session.
For a megolm-encrypted event, it is inferred from the Olm message which established the megolm session
Returns
Section titled “Returns”string | null
getServerAggregatedRelation()
Section titled “getServerAggregatedRelation()”getServerAggregatedRelation<
T>(relType):T|undefined
Defined in: src/models/event.ts:1550
Type Parameters
Section titled “Type Parameters”T
Parameters
Section titled “Parameters”relType
Section titled “relType”string
Returns
Section titled “Returns”T | undefined
getStateKey()
Section titled “getStateKey()”getStateKey():
string|undefined
Defined in: src/models/event.ts:757
Get the event state_key if it has one. If necessary, this will perform
string-unpacking on the state key, as per MSC4362. This will return
undefined for message events.
Returns
Section titled “Returns”string | undefined
The event’s state_key.
getThread()
Section titled “getThread()”getThread():
Thread|undefined
Defined in: src/models/event.ts:1756
Get the instance of the thread associated with the current event
Returns
Section titled “Returns”Thread | undefined
getTs()
Section titled “getTs()”getTs():
number
Defined in: src/models/event.ts:579
Get the timestamp of this event.
Returns
Section titled “Returns”number
The event timestamp, e.g. 1433502692297
getTxnId()
Section titled “getTxnId()”getTxnId():
string|undefined
Defined in: src/models/event.ts:1730
Returns
Section titled “Returns”string | undefined
getType()
Section titled “getType()”getType():
string
Defined in: src/models/event.ts:548
Get the (decrypted, if necessary) type of event.
Returns
Section titled “Returns”string
The event type, e.g. m.room.message
getUnsigned()
Section titled “getUnsigned()”getUnsigned():
IUnsigned
Defined in: src/models/event.ts:1146
Returns
Section titled “Returns”getWireContent()
Section titled “getWireContent()”getWireContent():
IContent
Defined in: src/models/event.ts:653
Get the (possibly encrypted) event content JSON that will be sent to the hub.
Returns
Section titled “Returns”The event content JSON, or an empty object.
getWireStateKey()
Section titled “getWireStateKey()”getWireStateKey():
string|undefined
Defined in: src/models/event.ts:770
Get the raw event state_key if it has one. This may be string-packed as per
MSC4362 if the state event is encrypted. This will return undefined
for message events.
Returns
Section titled “Returns”string | undefined
The event’s state_key.
getWireType()
Section titled “getWireType()”getWireType():
string
Defined in: src/models/event.ts:561
Get the (possibly encrypted) type of the event that will be sent to the hub.
Returns
Section titled “Returns”string
The event type.
handleRemoteEcho()
Section titled “handleRemoteEcho()”handleRemoteEcho(
event):void
Defined in: src/models/event.ts:1429
Replace the event property and recalculate any properties based on it.
Parameters
Section titled “Parameters”object
the object to assign to the event property
Returns
Section titled “Returns”void
hasAssociation()
Section titled “hasAssociation()”hasAssociation():
boolean
Defined in: src/models/event.ts:1615
Checks if this event is associated with another event. See getAssociatedId.
Returns
Section titled “Returns”boolean
isBeingDecrypted()
Section titled “isBeingDecrypted()”isBeingDecrypted():
boolean
Defined in: src/models/event.ts:841
Check if this event is currently being decrypted.
Returns
Section titled “Returns”boolean
True if this event is currently being decrypted, else false.
isCancelled()
Section titled “isCancelled()”isCancelled():
boolean
Defined in: src/models/event.ts:1651
Gets whether or not the event is flagged as cancelled. See flagCancelled() for more information.
Returns
Section titled “Returns”boolean
True if the event is cancelled, false otherwise.
isDecryptionFailure()
Section titled “isDecryptionFailure()”isDecryptionFailure():
boolean
Defined in: src/models/event.ts:857
Check if this event is an encrypted event which we failed to decrypt
(This implies that we might retry decryption at some point in the future)
Returns
Section titled “Returns”boolean
True if this event is an encrypted event which we couldn’t decrypt.
isEncrypted()
Section titled “isEncrypted()”isEncrypted():
boolean
Defined in: src/models/event.ts:1064
Check if the event is encrypted.
Returns
Section titled “Returns”boolean
True if this event is encrypted.
isEquivalentTo()
Section titled “isEquivalentTo()”isEquivalentTo(
otherEvent?):boolean
Defined in: src/models/event.ts:1688
Determines if this event is equivalent to the given event. This only checks the event object itself, not the other properties of the event. Intended for use with toSnapshot() to identify events changing.
Parameters
Section titled “Parameters”otherEvent?
Section titled “otherEvent?”DigitalWorldEvent
The other event to check against.
Returns
Section titled “Returns”boolean
True if the events are the same, false otherwise.
isKeySourceUntrusted()
Section titled “isKeySourceUntrusted()”isKeySourceUntrusted():
false
Defined in: src/models/event.ts:1133
Returns
Section titled “Returns”false
isRedacted()
Section titled “isRedacted()”isRedacted():
boolean
Defined in: src/models/event.ts:1315
Check if this event has been redacted
Returns
Section titled “Returns”boolean
True if this event has been redacted
isRedaction()
Section titled “isRedaction()”isRedaction():
boolean
Defined in: src/models/event.ts:1324
Check if this event is a redaction of another event
Returns
Section titled “Returns”boolean
True if this event is a redaction
isRelation()
Section titled “isRelation()”isRelation(
relType?):boolean
Defined in: src/models/event.ts:1484
Get whether the event is a relation event, and of a given type if
relType is passed in. State events cannot be relation events
Parameters
Section titled “Parameters”relType?
Section titled “relType?”string
if given, checks that the relation is of the given type
Returns
Section titled “Returns”boolean
isSending()
Section titled “isSending()”isSending():
boolean
Defined in: src/models/event.ts:1458
Whether the event is in any phase of sending, send failure, waiting for remote echo, etc.
Returns
Section titled “Returns”boolean
isState()
Section titled “isState()”isState():
boolean
Defined in: src/models/event.ts:778
Check if this event is a state event.
Returns
Section titled “Returns”boolean
True if this is a state event.
isVisibilityEvent()
Section titled “isVisibilityEvent()”isVisibilityEvent():
boolean
Defined in: src/models/event.ts:1372
Check if this event alters the visibility of another event, as per https://github.com/matrix-org/matrix-doc/pull/3531.
Returns
Section titled “Returns”boolean
True if this event alters the visibility of another event.
listenerCount()
Section titled “listenerCount()”listenerCount(
event):number
Defined in: src/models/typed-event-emitter.ts:115
Returns the number of listeners listening to the event named event.
Parameters
Section titled “Parameters”EventEmitterEvents | DigitalWorldEventEmittedEvents
The name of the event being listened for
Returns
Section titled “Returns”number
Inherited from
Section titled “Inherited from”TypedEventEmitter.listenerCount
listeners()
Section titled “listeners()”listeners(
event):Function[]
Defined in: src/models/typed-event-emitter.ts:122
Returns a copy of the array of listeners for the event named event.
Parameters
Section titled “Parameters”EventEmitterEvents | DigitalWorldEventEmittedEvents
Returns
Section titled “Returns”Function[]
Inherited from
Section titled “Inherited from”localRedactionEvent()
Section titled “localRedactionEvent()”localRedactionEvent():
DigitalWorldEvent|null
Defined in: src/models/event.ts:1594
Returns the event that wants to redact this event, but hasn’t been sent yet.
Returns
Section titled “Returns”DigitalWorldEvent | null
the event
makeRedacted()
Section titled “makeRedacted()”makeRedacted(
redactionEvent,room):void
Defined in: src/models/event.ts:1227
Update the content of an event in the same way it would be by the server if it were redacted before it was sent to us
Parameters
Section titled “Parameters”redactionEvent
Section titled “redactionEvent”DigitalWorldEvent
event causing the redaction
the room in which the event exists
Returns
Section titled “Returns”void
makeReplaced()
Section titled “makeReplaced()”makeReplaced(
newEvent?):void
Defined in: src/models/event.ts:1517
Set an event that replaces the content of this event, through an m.replace relation.
Parameters
Section titled “Parameters”newEvent?
Section titled “newEvent?”DigitalWorldEvent
the event with the replacing content, if any.
Returns
Section titled “Returns”void
Remarks
Section titled “Remarks”Fires DigitalWorldEventEvent.Replaced
markLocallyRedacted()
Section titled “markLocallyRedacted()”markLocallyRedacted(
redactionEvent):void
Defined in: src/models/event.ts:1163
Parameters
Section titled “Parameters”redactionEvent
Section titled “redactionEvent”DigitalWorldEvent
Returns
Section titled “Returns”void
messageVisibility()
Section titled “messageVisibility()”messageVisibility():
MessageVisibility
Defined in: src/models/event.ts:1214
Return instructions to display or hide the message.
Returns
Section titled “Returns”Instructions determining whether the message should be displayed.
off<
T>(event,listener):this
Defined in: src/models/typed-event-emitter.ts:129
Alias for removeListener
Type Parameters
Section titled “Type Parameters”T extends EventEmitterEvents | DigitalWorldEventEmittedEvents
Parameters
Section titled “Parameters”T
listener
Section titled “listener”Listener<DigitalWorldEventEmittedEvents, DigitalWorldEventHandlerMap, T>
Returns
Section titled “Returns”this
Inherited from
Section titled “Inherited from”on<
T>(event,listener):this
Defined in: src/models/typed-event-emitter.ts:150
Adds the listener function to the end of the listeners array for the
event named event.
No checks are made to see if the listener has already been added. Multiple calls
passing the same combination of event and listener will result in the listener
being added, and called, multiple times.
By default, event listeners are invoked in the order they are added. The prependListener method can be used as an alternative to add the event listener to the beginning of the listeners array.
Type Parameters
Section titled “Type Parameters”T extends EventEmitterEvents | DigitalWorldEventEmittedEvents
Parameters
Section titled “Parameters”T
The name of the event.
listener
Section titled “listener”Listener<DigitalWorldEventEmittedEvents, DigitalWorldEventHandlerMap, T>
The callback function
Returns
Section titled “Returns”this
a reference to the EventEmitter, so that calls can be chained.
Inherited from
Section titled “Inherited from”once()
Section titled “once()”once<
T>(event,listener):this
Defined in: src/models/typed-event-emitter.ts:169
Adds a one-time listener function for the event named event. The
next time event is triggered, this listener is removed and then invoked.
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 prependOnceListener method can be used as an alternative to add the event listener to the beginning of the listeners array.
Type Parameters
Section titled “Type Parameters”T extends EventEmitterEvents | DigitalWorldEventEmittedEvents
Parameters
Section titled “Parameters”T
The name of the event.
listener
Section titled “listener”Listener<DigitalWorldEventEmittedEvents, DigitalWorldEventHandlerMap, T>
The callback function
Returns
Section titled “Returns”this
a reference to the EventEmitter, so that calls can be chained.
Inherited from
Section titled “Inherited from”prependListener()
Section titled “prependListener()”prependListener<
T>(event,listener):this
Defined in: src/models/typed-event-emitter.ts:186
Adds the listener function to the beginning of the listeners array for the
event named event.
No checks are made to see if the listener has already been added. Multiple calls
passing the same combination of event and listener will result in the listener
being added, and called, multiple times.
Type Parameters
Section titled “Type Parameters”T extends EventEmitterEvents | DigitalWorldEventEmittedEvents
Parameters
Section titled “Parameters”T
The name of the event.
listener
Section titled “listener”Listener<DigitalWorldEventEmittedEvents, DigitalWorldEventHandlerMap, T>
The callback function
Returns
Section titled “Returns”this
a reference to the EventEmitter, so that calls can be chained.
Inherited from
Section titled “Inherited from”TypedEventEmitter.prependListener
prependOnceListener()
Section titled “prependOnceListener()”prependOnceListener<
T>(event,listener):this
Defined in: src/models/typed-event-emitter.ts:202
Adds a one-timelistener function for the event named event to the beginning of the listeners array.
The next time event is triggered, this listener is removed, and then invoked.
Type Parameters
Section titled “Type Parameters”T extends EventEmitterEvents | DigitalWorldEventEmittedEvents
Parameters
Section titled “Parameters”T
The name of the event.
listener
Section titled “listener”Listener<DigitalWorldEventEmittedEvents, DigitalWorldEventHandlerMap, T>
The callback function
Returns
Section titled “Returns”this
a reference to the EventEmitter, so that calls can be chained.
Inherited from
Section titled “Inherited from”TypedEventEmitter.prependOnceListener
rawListeners()
Section titled “rawListeners()”rawListeners(
event):Function[]
Defined in: src/models/typed-event-emitter.ts:243
Returns a copy of the array of listeners for the event named eventName,
including any wrappers (such as those created by .once()).
Parameters
Section titled “Parameters”EventEmitterEvents | DigitalWorldEventEmittedEvents
Returns
Section titled “Returns”Function[]
Inherited from
Section titled “Inherited from”TypedEventEmitter.rawListeners
removeAllListeners()
Section titled “removeAllListeners()”removeAllListeners(
event?):this
Defined in: src/models/typed-event-emitter.ts:219
Removes all listeners, or those of the specified event.
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).
Parameters
Section titled “Parameters”event?
Section titled “event?”EventEmitterEvents | DigitalWorldEventEmittedEvents
The name of the event. If undefined, all listeners everywhere are removed.
Returns
Section titled “Returns”this
a reference to the EventEmitter, so that calls can be chained.
Inherited from
Section titled “Inherited from”TypedEventEmitter.removeAllListeners
removeListener()
Section titled “removeListener()”removeListener<
T>(event,listener):this
Defined in: src/models/typed-event-emitter.ts:232
Removes the specified listener from the listener array for the event named event.
Type Parameters
Section titled “Type Parameters”T extends EventEmitterEvents | DigitalWorldEventEmittedEvents
Parameters
Section titled “Parameters”T
listener
Section titled “listener”Listener<DigitalWorldEventEmittedEvents, DigitalWorldEventHandlerMap, T>
Returns
Section titled “Returns”this
a reference to the EventEmitter, so that calls can be chained.
Inherited from
Section titled “Inherited from”TypedEventEmitter.removeListener
replaceLocalEventId()
Section titled “replaceLocalEventId()”replaceLocalEventId(
eventId):void
Defined in: src/models/event.ts:1472
Parameters
Section titled “Parameters”eventId
Section titled “eventId”string
Returns
Section titled “Returns”void
replacingEvent()
Section titled “replacingEvent()”replacingEvent():
DigitalWorldEvent|null
Defined in: src/models/event.ts:1571
Returns the event replacing the content of this event, if any. Replacements are aggregated on the server, so this would only return an event in case it came down the sync, or for local echo of edits.
Returns
Section titled “Returns”DigitalWorldEvent | null
replacingEventDate()
Section titled “replacingEventDate()”replacingEventDate():
Date|undefined
Defined in: src/models/event.ts:1578
Returns the origin_server_ts of the event replacing the content of this event, if any.
Returns
Section titled “Returns”Date | undefined
replacingEventId()
Section titled “replacingEventId()”replacingEventId():
string|undefined
Defined in: src/models/event.ts:1557
Returns the event ID of the event replacing the content of this event, if any.
Returns
Section titled “Returns”string | undefined
setMaxListeners()
Section titled “setMaxListeners()”setMaxListeners(
n):this
Defined in: node_modules/.pnpm/@types+node@22.20.0/node_modules/@types/node/events.d.ts:813
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
Section titled “Parameters”number
Returns
Section titled “Returns”this
v0.3.5
Inherited from
Section titled “Inherited from”TypedEventEmitter.setMaxListeners
setPushDetails()
Section titled “setPushDetails()”setPushDetails(
pushActions?,rule?):void
Defined in: src/models/event.ts:1418
Set the push details for this event.
Parameters
Section titled “Parameters”pushActions?
Section titled “pushActions?”IActionsObject
push actions
the executed push rule
Returns
Section titled “Returns”void
setStatus()
Section titled “setStatus()”setStatus(
status):void
Defined in: src/models/event.ts:1467
Update the event’s sending status and emit an event as well.
Parameters
Section titled “Parameters”status
Section titled “status”EventStatus | null
The new status
Returns
Section titled “Returns”void
setThread()
Section titled “setThread()”setThread(
thread?):void
Defined in: src/models/event.ts:1738
Set the instance of a thread associated with the current event
Parameters
Section titled “Parameters”thread?
Section titled “thread?”the thread
Returns
Section titled “Returns”void
setThreadId()
Section titled “setThreadId()”setThreadId(
threadId?):void
Defined in: src/models/event.ts:1760
Parameters
Section titled “Parameters”threadId?
Section titled “threadId?”string
Returns
Section titled “Returns”void
setTxnId()
Section titled “setTxnId()”setTxnId(
txnId):void
Defined in: src/models/event.ts:1726
Parameters
Section titled “Parameters”string
Returns
Section titled “Returns”void
setUnsigned()
Section titled “setUnsigned()”setUnsigned(
unsigned):void
Defined in: src/models/event.ts:1150
Parameters
Section titled “Parameters”unsigned
Section titled “unsigned”Returns
Section titled “Returns”void
shouldAttemptDecryption()
Section titled “shouldAttemptDecryption()”shouldAttemptDecryption():
boolean
Defined in: src/models/event.ts:866
Returns
Section titled “Returns”boolean
toJSON()
Section titled “toJSON()”toJSON():
object
Defined in: src/models/event.ts:1713
Summarise the event as JSON.
If encrypted, include both the decrypted and encrypted view of the event.
This is named toJSON for use with JSON.stringify which checks objects
for functions named toJSON and will call them to customise the output
if they are defined.
WARNING Do not log the result of this method; otherwise, it will end up in rageshakes, leading to a privacy violation.
Returns
Section titled “Returns”object
toSnapshot()
Section titled “toSnapshot()”toSnapshot():
DigitalWorldEvent
Defined in: src/models/event.ts:1669
Get a copy/snapshot of this event. The returned copy will be loosely linked back to this instance, though will have “frozen” event information. Other properties of this DigitalWorldEvent instance will be copied verbatim, which can mean they are in reference to this instance despite being on the copy too. The reference the snapshot uses does not change, however members aside from the underlying event will not be deeply cloned, thus may be mutated internally. For example, the sender profile will be copied over at snapshot time, and the sender profile internally may mutate without notice to the consumer.
This is meant to be used to snapshot the event details themselves, not the features (such as sender) surrounding the event.
Returns
Section titled “Returns”DigitalWorldEvent
A snapshot of this event.
unmarkLocallyRedacted()
Section titled “unmarkLocallyRedacted()”unmarkLocallyRedacted():
boolean
Defined in: src/models/event.ts:1154
Returns
Section titled “Returns”boolean
updateAssociatedId()
Section titled “updateAssociatedId()”updateAssociatedId(
eventId):void
Defined in: src/models/event.ts:1627
Update the related id with a new one.
Used to replace a local id with remote one before sending an event with a related id.
Parameters
Section titled “Parameters”eventId
Section titled “eventId”string
the new event id
Returns
Section titled “Returns”void
addAbortListener()
Section titled “addAbortListener()”
staticaddAbortListener(signal,resource):Disposable
Defined in: node_modules/.pnpm/@types+node@22.20.0/node_modules/@types/node/events.d.ts:403
Listens once to the abort event on the provided 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.
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.
Returns a disposable so that it may be unsubscribed from more easily.
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
Section titled “Parameters”signal
Section titled “signal”AbortSignal
resource
Section titled “resource”(event) => void
Returns
Section titled “Returns”Disposable
Disposable that removes the abort listener.
v20.5.0
Inherited from
Section titled “Inherited from”TypedEventEmitter.addAbortListener
getEventListeners()
Section titled “getEventListeners()”
staticgetEventListeners(emitter,name):Function[]
Defined in: node_modules/.pnpm/@types+node@22.20.0/node_modules/@types/node/events.d.ts:325
Returns a copy of the array of listeners for the event named eventName.
For EventEmitters this behaves exactly the same as calling .listeners on
the emitter.
For EventTargets this is the only way to get the event listeners for the
event target. This is useful for debugging and diagnostic purposes.
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
Section titled “Parameters”emitter
Section titled “emitter”EventEmitter<DefaultEventMap> | EventTarget
string | symbol
Returns
Section titled “Returns”Function[]
v15.2.0, v14.17.0
Inherited from
Section titled “Inherited from”TypedEventEmitter.getEventListeners
getMaxListeners()
Section titled “getMaxListeners()”
staticgetMaxListeners(emitter):number
Defined in: node_modules/.pnpm/@types+node@22.20.0/node_modules/@types/node/events.d.ts:354
Returns the currently set max amount of listeners.
For EventEmitters this behaves exactly the same as calling .getMaxListeners on
the emitter.
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.
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
Section titled “Parameters”emitter
Section titled “emitter”EventEmitter<DefaultEventMap> | EventTarget
Returns
Section titled “Returns”number
v19.9.0
Inherited from
Section titled “Inherited from”TypedEventEmitter.getMaxListeners
listenerCount()
Section titled “listenerCount()”
staticlistenerCount(emitter,eventName):number
Defined in: node_modules/.pnpm/@types+node@22.20.0/node_modules/@types/node/events.d.ts:297
A class method that returns the number of listeners for the given eventName registered on the given emitter.
import { EventEmitter, listenerCount } from 'node:events';
const myEmitter = new EventEmitter();myEmitter.on('event', () => {});myEmitter.on('event', () => {});console.log(listenerCount(myEmitter, 'event'));// Prints: 2Parameters
Section titled “Parameters”emitter
Section titled “emitter”EventEmitter
The emitter to query
eventName
Section titled “eventName”string | symbol
The event name
Returns
Section titled “Returns”number
v0.9.12
Inherited from
Section titled “Inherited from”TypedEventEmitter.listenerCount
Call Signature
Section titled “Call Signature”
staticon(emitter,eventName,options?):AsyncIterator<any[]>
Defined in: node_modules/.pnpm/@types+node@22.20.0/node_modules/@types/node/events.d.ts:270
import { on, EventEmitter } from 'node:events';import process from 'node:process';
const ee = new EventEmitter();
// Emit later onprocess.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. console.log(event); // prints ['bar'] [42]}// Unreachable hereReturns an AsyncIterator that iterates eventName events. It will throw
if the EventEmitter emits 'error'. It removes all listeners when
exiting the loop. The value returned by each iteration is an array
composed of the emitted event arguments.
An AbortSignal can be used to cancel waiting on events:
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. 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:
import { on, EventEmitter } from 'node:events';import process from 'node:process';
const ee = new EventEmitter();
// Emit later onprocess.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 emittedconsole.log('done'); // prints 'done'Parameters
Section titled “Parameters”emitter
Section titled “emitter”EventEmitter
eventName
Section titled “eventName”string | symbol
options?
Section titled “options?”StaticEventEmitterIteratorOptions
Returns
Section titled “Returns”AsyncIterator<any[]>
An AsyncIterator that iterates eventName events emitted by the emitter
v13.6.0, v12.16.0
Inherited from
Section titled “Inherited from”Call Signature
Section titled “Call Signature”
staticon(emitter,eventName,options?):AsyncIterator<any[]>
Defined in: node_modules/.pnpm/@types+node@22.20.0/node_modules/@types/node/events.d.ts:275
import { on, EventEmitter } from 'node:events';import process from 'node:process';
const ee = new EventEmitter();
// Emit later onprocess.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. console.log(event); // prints ['bar'] [42]}// Unreachable hereReturns an AsyncIterator that iterates eventName events. It will throw
if the EventEmitter emits 'error'. It removes all listeners when
exiting the loop. The value returned by each iteration is an array
composed of the emitted event arguments.
An AbortSignal can be used to cancel waiting on events:
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. 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:
import { on, EventEmitter } from 'node:events';import process from 'node:process';
const ee = new EventEmitter();
// Emit later onprocess.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 emittedconsole.log('done'); // prints 'done'Parameters
Section titled “Parameters”emitter
Section titled “emitter”EventTarget
eventName
Section titled “eventName”string
options?
Section titled “options?”StaticEventEmitterIteratorOptions
Returns
Section titled “Returns”AsyncIterator<any[]>
An AsyncIterator that iterates eventName events emitted by the emitter
v13.6.0, v12.16.0
Inherited from
Section titled “Inherited from”once()
Section titled “once()”Call Signature
Section titled “Call Signature”
staticonce(emitter,eventName,options?):Promise<any[]>
Defined in: node_modules/.pnpm/@types+node@22.20.0/node_modules/@types/node/events.d.ts:184
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.
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.
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. 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:
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 boomAn AbortSignal can be used to cancel waiting for the event:
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 eventee.emit('foo'); // Prints: Waiting for the event was canceled!Parameters
Section titled “Parameters”emitter
Section titled “emitter”EventEmitter
eventName
Section titled “eventName”string | symbol
options?
Section titled “options?”StaticEventEmitterOptions
Returns
Section titled “Returns”Promise<any[]>
v11.13.0, v10.16.0
Inherited from
Section titled “Inherited from”Call Signature
Section titled “Call Signature”
staticonce(emitter,eventName,options?):Promise<any[]>
Defined in: node_modules/.pnpm/@types+node@22.20.0/node_modules/@types/node/events.d.ts:189
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.
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.
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. 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:
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 boomAn AbortSignal can be used to cancel waiting for the event:
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 eventee.emit('foo'); // Prints: Waiting for the event was canceled!Parameters
Section titled “Parameters”emitter
Section titled “emitter”EventTarget
eventName
Section titled “eventName”string
options?
Section titled “options?”StaticEventEmitterOptions
Returns
Section titled “Returns”Promise<any[]>
v11.13.0, v10.16.0
Inherited from
Section titled “Inherited from”setMaxListeners()
Section titled “setMaxListeners()”
staticsetMaxListeners(n?, …eventTargets):void
Defined in: node_modules/.pnpm/@types+node@22.20.0/node_modules/@types/node/events.d.ts:369
import { setMaxListeners, EventEmitter } from 'node:events';
const target = new EventTarget();const emitter = new EventEmitter();
setMaxListeners(5, target, emitter);Parameters
Section titled “Parameters”number
A non-negative number. The maximum number of listeners per EventTarget event.
eventTargets
Section titled “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.
Returns
Section titled “Returns”void
v15.4.0