Class Client

Represents the bot's client.

Hierarchy

Constructors

Properties

Accessors

Methods

addListener archiveChannel awardMember awardRole bulkCalendarRsvpUpdate bulkDeleteReactions completeListItem connect createAnnouncement createAnnouncementComment createBan createCalendarComment createCalendarEvent createCalendarEventSeries createChannel createDoc createDocComment createForumComment createForumThread createGuildGroup createGuildRole createListItem createMessage createReaction createReactionToSubcategory createWebhook deleteAnnouncement deleteAnnouncementComment deleteCalendarComment deleteCalendarEvent deleteCalendarEventSeries deleteCalendarRsvp deleteChannel deleteDoc deleteDocComment deleteForumComment deleteForumThread deleteGuildGroup deleteGuildRole deleteListItem deleteMessage deleteReaction deleteReactionFromSubcategory deleteUserStatus deleteWebhook disconnect editAnnouncement editAnnouncementComment editCalendarComment editCalendarEvent editCalendarEventSeries editCalendarRsvp editChannel editDoc editDocComment editForumComment editForumThread editGuildGroup editGuildRole editListItem editMember editMessage editWebhook emit eventNames getAnnouncement getAnnouncementComment getAnnouncementComments getAnnouncements getBan getBans getCalendarEvent getCalendarEventComment getCalendarEventComments getCalendarEvents getCalendarRsvp getCalendarRsvps getChannel getDoc getDocComment getDocComments getDocs getForumComment getForumComments getForumThread getForumThreads getGuild getGuildGroup getGuildGroups getGuildRole getGuildRoles getGuildSubscription getGuildSubscriptions getListItem getListItems getMaxListeners getMember getMemberPermissions getMembers getMessage getMessages getUser getUserGuilds getWebhook getWebhooks listenerCount listeners lockForumThread memberAddGroup memberAddRole memberRemoveGroup memberRemoveRole off on once pinForumThread pinMessage prependListener prependOnceListener rawListeners removeAllListeners removeBan removeListener removeMember restoreChannel setMaxListeners setMemberXP uncompleteListItem unlockForumThread unpinForumThread unpinMessage updateRolePermission updateUserStatus getEventListeners listenerCount on once setMaxListeners

Constructors

Properties

guilds: TypedCollection<string, APIGuild, Guild, []>

Cached guilds.

Client's params, including bot's token & rest options.

REST methods.

startTime: number
user?: UserClient

Client's user.

users: TypedCollection<string, APIUser, User, []>

Cached users.

util: Util

Utils

Websocket Manager.

captureRejectionSymbol: typeof captureRejectionSymbol
captureRejections: boolean

Sets or gets the default captureRejection value for all emitters.

defaultMaxListeners: number
errorMonitor: typeof errorMonitor

This symbol shall be used to install a listener for only monitoring 'error' events. Listeners installed using this symbol are called before the regular 'error' listeners are called.

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.

Accessors

Methods

  • Archive a channel.

    Parameters

    • channelID: string

      ID of the channel to archive.

    Returns Promise<void>

  • Award a member using the built-in EXP system.

    Parameters

    • guildID: string

      ID of a guild.

    • memberID: string

      ID of a member.

    • amount: number

      Amount of experience.

    Returns Promise<number>

  • Award every members of a guild having a role using the built-in EXP system.

    Parameters

    • guildID: string

      ID of a guild.

    • roleID: number

      ID of a role.

    • amount: number

      Amount of experience.

    Returns Promise<void>

  • Bulk create/update calendar rsvps.

    Parameters

    • channelID: string

      ID of the Calendar channel.

    • eventID: number

      ID of a calendar event.

    • memberIDs: string[]

      List of multiple member ids.

    • options: EditCalendarRSVPOptions

      Update options.

    Returns Promise<void>

  • Bulk delete every reaction from a target.

    Parameters

    • channelID: string

      ID of a channel.

    • channelType: "ChannelMessage"

      Type of channel.

    • targetID: string | number

      Target to remove reactions from it.

    • Optional filter: DELETEMessageReactionQuery

    Returns Promise<void>

  • Mark a list item as completed.

    Parameters

    • channelID: string

      ID of a "Lists" channel.

    • itemID: string

      ID of a list item.

    Returns Promise<void>

  • Ban a guild member.

    Parameters

    • guildID: string

      ID of the guild the member is in.

    • memberID: string

      ID of the member to ban.

    • Optional reason: string

      The reason of the ban.

    Returns Promise<BannedMember>

  • Create an event into a "Calendar" channel.

    Parameters

    • channelID: string

      ID of a "Calendar" channel.

    • options: CreateCalendarEventOptions

      Event options.

    • Optional createSeries: {
          endDate?: string;
          endsAfterOccurrences?: number;
          every?: {
              count: number;
              interval: "day" | "week" | "month" | "year";
          };
          on?: ("sunday" | "monday" | "tuesday" | "wednesday" | "thursday" | "friday" | "saturday")[];
          type: "once" | "everyDay" | "everyWeek" | "everyMonth" | "custom";
      }

      (optional) Create a series. (event's repetition)

      • Optional endDate?: string

        The ISO 8601 timestamp that the event ends at. Used to control the end date of the event repeat (only used when type is custom; if used with endsAfterOccurrences, the earliest resultant date of the two will be used)

      • Optional endsAfterOccurrences?: number

        Used to control the end date of the event repeat (only used when type is custom; if used with endDate, the earliest resultant date of the two will be used) (max 24)

      • Optional every?: {
            count: number;
            interval: "day" | "week" | "month" | "year";
        }

        Apply further clarification to your events. This must have type set to custom

        • count: number

          How often between your interval the event should repeat. For example, 1 would be every interval, 2 would be every second occurrence of the interval

        • interval: "day" | "week" | "month" | "year"

          Coupled with count, this indicates the time range you are repeating your event over

      • Optional on?: ("sunday" | "monday" | "tuesday" | "wednesday" | "thursday" | "friday" | "saturday")[]

        Used to control the day of the week that the event should repeat on (only used when type is custom and when every.interval is week) (min items 1)

      • type: "once" | "everyDay" | "everyWeek" | "everyMonth" | "custom"

        How often you want your event to repeat (important note: this will repeat for the next 180 days unless custom is defined) (default once)

    Returns Promise<CalendarEvent>

  • The Guilded API only allows series on the event's creation.

    Use createCalendarEvent and set the createSeries property to create a series.

    Returns Error

  • Create a new item in a list channel.

    Parameters

    • channelID: string

      ID of a "Lists" channel.

    • content: string

      String content of the new item.

    • Optional note: {
          content: string;
      }

      Add a note to the new item.

      • content: string

        The note of the list item

    Returns Promise<ListItem>

  • Add a reaction to a specified target.

    Parameters

    • channelID: string

      ID of a channel that supports reaction.

    • channelType: ChannelReactionTypes

      Type of the selected channel. (e.g: "ChannelMessage")

    • targetID: string | number

      ID of the target you'd like to add the reaction to. (e.g: a message id)

    • reaction: number

      ID of the reaction.

    Returns Promise<void>

  • Add a reaction to a target from a subcategory (e.g: a comment from Forum Thread)

    Parameters

    • channelID: string

      ID of a channel that supports reaction.

    • subcategoryType: ChannelSubcategoryReactionTypes

      Type of the selected subcategory. (e.g: "CalendarEvent")

    • subcategoryID: string | number

      ID of the subcategory you selected.

    • targetID: string | number

      ID of the target you'd like to add the reaction to. (e.g: a comment id)

    • reaction: number

      ID of the reaction to add.

    Returns Promise<void>

  • Create a webhook

    Parameters

    • guildID: string

      ID of a guild.

    • channelID: string

      ID of a channel.

    • name: string

      Name of the new webhook.

    Returns Promise<Webhook>

  • Delete an announcement.

    Parameters

    • channelID: string

      ID of an Announcement channel.

    • announcementID: string

      ID of the announcement to delete.

    Returns Promise<void>

  • Delete an announcement comment.

    Parameters

    • channelID: string

      ID of an Announcement channel.

    • announcementID: string

      ID of the announcement where the comment is in.

    • commentID: number

      ID of the comment to delete.

    Returns Promise<void>

  • Delete a comment from a calendar event.

    Parameters

    • channelID: string

      ID of the channel containing the event.

    • eventID: number

      ID of the event containing the comment.

    • commentID: number

      ID of the comment to delete.

    Returns Promise<void>

  • Delete an event from a "Calendar" channel.

    Parameters

    • channelID: string

      ID of a "Calendar" channel.

    • eventID: number

      ID of a calendar event.

    Returns Promise<void>

  • Delete a CalendarEventSeries.

    Parameters

    • channelID: string

      ID of the channel.

    • eventID: number

      ID of the event.

    • seriesID: string

      ID of the series.

    Returns Promise<void>

  • Delete a RSVP from a calendar event.

    Parameters

    • channelID: string

      ID of a "Calendar" channel.

    • eventID: number

      ID of a calendar event.

    • memberID: string

      ID of a member.

    Returns Promise<void>

  • Delete a channel.

    Parameters

    • channelID: string

      ID of the channel you'd like to delete.

    Returns Promise<void>

  • Delete a doc from a "Docs" channel.

    Parameters

    • channelID: string

      ID of a "Docs" channel.

    • docID: number

      ID of a doc.

    Returns Promise<void>

  • Delete a doc comment.

    Parameters

    • channelID: string

      ID of the docs channel.

    • docID: number

      ID of the doc.

    • commentID: number

      ID of the comment to delete.

    Returns Promise<void>

  • Delete a forum thread comment.

    Parameters

    • channelID: string

      ID of a "Forums" channel.

    • threadID: number

      ID of a forum thread.

    • commentID: number

      ID of a forum thread comment.

    Returns Promise<void>

  • Delete a forum thread from a specific forum channel

    Parameters

    • channelID: string

      ID of a "Forums" channel.

    • threadID: number

      ID of a forum thread.

    Returns Promise<void>

  • Delete a guild group

    Parameters

    • guildID: string

      ID of the guild where the group is in.

    • groupID: string

      ID of the group to delete.

    Returns Promise<void>

  • Delete a guild role.

    Parameters

    • guildID: string

      ID of the guild where the role to delete is in

    • roleID: number

      ID of the role to delete

    Returns Promise<void>

  • Delete an item from a list channel.

    Parameters

    • channelID: string

      ID of a "Lists" channel.

    • itemID: string

      ID of a list item.

    Returns Promise<void>

  • Delete a specific message.

    Parameters

    • channelID: string

      ID of the channel containing the message.

    • messageID: string

      ID of the message you'd like to delete.

    Returns Promise<void>

  • Remove a reaction from a specified message.

    Parameters

    • channelID: string

      ID of a channel that supports reaction.

    • channelType: ChannelReactionTypes

      Type of the selected channel. (e.g: "ChannelMessage")

    • targetID: string | number

      ID of the target you'd like to add the reaction from. (e.g: a message id)

    • reaction: number

      ID of the reaction.

    Returns Promise<void>

  • Remove a reaction from a target from a subcategory (e.g: a comment from Forum Thread)

    Parameters

    • channelID: string

      ID of a channel that supports reaction.

    • subcategoryType: ChannelSubcategoryReactionTypes

      Type of the selected subcategory. (e.g: "CalendarEvent")

    • subcategoryID: string | number

      ID of the subcategory you selected.

    • targetID: string | number

      ID of the target you'd like to remove the reaction to. (e.g: a comment id)

    • reaction: number

      ID of the reaction to add.

    Returns Promise<void>

  • Delete a user's status, this includes the bot's one.

    Parameters

    • userID: string

      User ID (@me can be used).

    Returns Promise<void>

  • Delete a webhook

    Parameters

    • guildID: string

      ID of a guild.

    • webhookID: string

      ID of an existent webhook.

    Returns Promise<void>

  • Disconnect from Guilded.

    Parameters

    • Optional crashOnDisconnect: boolean

      If set, throws an error to stop the process.

    Returns void

  • Edit a CalendarEventSeries.

    Parameters

    • channelID: string

      ID of the channel.

    • eventID: number

      ID of the event.

    • seriesID: string

      ID of the series.

    • options: undefined | {
          endDate?: string;
          endsAfterOccurrences?: number;
          every?: {
              count: number;
              interval: "day" | "week" | "month" | "year";
          };
          on?: ("sunday" | "monday" | "tuesday" | "wednesday" | "thursday" | "friday" | "saturday")[];
          type: "once" | "everyDay" | "everyWeek" | "everyMonth" | "custom";
      }

      Edit repetition options.

    Returns Promise<void>

  • Edit a doc from a "Docs" channel.

    Parameters

    • channelID: string

      ID of a "Docs" channel.

    • docID: number

      ID of a doc.

    • options: EditDocOptions

      Edit options.

    Returns Promise<Doc>

  • Edit an item from a list channel.

    Parameters

    • channelID: string

      ID of a "Lists" channel.

    • itemID: string

      ID of a list item.

    • Optional options: {
          content?: string;
          note?: {
              content: string;
          };
      }

      Edit options.

      • Optional content?: string
      • Optional note?: {
            content: string;
        }
        • content: string

          The note of the list item

    Returns Promise<ListItem>

  • Edit a member.

    Parameters

    • guildID: string

      ID of the guild the member is in.

    • memberID: string

      ID of the the member to edit.

    • options: EditMemberOptions

      Edit options.

    Returns Promise<void>

  • Edit a specific message coming from a specified channel.

    Type Parameters

    Parameters

    • channelID: string

      The ID of the channel.

    • messageID: string

      The ID of the message you'd like to edit.

    • newMessage: object

      object containing new message's options.

    Returns Promise<Message<T>>

  • Returns an array listing the events for which the emitter has registered listeners. The values in the array are strings or Symbols.

    const EventEmitter = require('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)[]

    Since

    v6.0.0

  • Get a specific announcement from a channel.

    Parameters

    • channelID: string

      ID of an Announcement channel.

    • announcementID: string

      ID of the announcement to get.

    Returns Promise<Announcement>

  • Get a specific comment from an announcement.

    Parameters

    • channelID: string

      ID of an Announcement channel.

    • announcementID: string

      ID of the announcement where the comment is in.

    • commentID: number

      ID of the comment to get.

    Returns Promise<AnnouncementComment>

  • This method is used to get a specific calendar event.

    Note: this method requires a "Calendar" channel.

    Parameters

    • channelID: string

      ID of a Calendar channel.

    • eventID: number

      ID of a Calendar event.

    Returns Promise<CalendarEvent>

  • This method is used to get a specific event comment coming from a calendar. Note: this method doesn't cache scheduled events due to the API's restrictions.

    Parameters

    • channelID: string

      ID of a "Calendar" channel.

    • eventID: number

      ID of an event containing the comment to get.

    • commentID: number

      ID of the comment to get.

    Returns Promise<CalendarEventComment>

  • This method is used to get a list of CalendarEventComment Note: due to API's restrictions, we're not able to cache scheduled events from this method.

    Parameters

    • channelID: string

      ID of a "Calendar" channel.

    • eventID: number

      ID of the event containing comments.

    Returns Promise<CalendarEventComment[]>

  • This method is used to get a specific CalendarEventRSVP.

    Note: this method requires a Calendar channel.

    Parameters

    • channelID: string

      ID of a Calendar channel

    • eventID: number

      ID of a Calendar Event

    • memberID: string

      ID of a Guild Member

    Returns Promise<CalendarEventRSVP>

  • This method is used to get a specific guild channel, if cached.

    Note: this method doesn't send a rest request, it only returns cached entities.

    Type Parameters

    Parameters

    • guildID: string
    • channelID: string

      The ID of the channel to get from cache.

    Returns undefined | T

  • This method is used to get a channel doc.

    Note: This method requires a "Docs" channel.

    Parameters

    • channelID: string

      ID of the Docs channel.

    • docID: number

      ID of the channel doc.

    Returns Promise<Doc>

  • Get a specific comment from a doc.

    Parameters

    • channelID: string

      ID of the channel containing the doc.

    • docID: number

      ID of the doc the comment is in.

    • commentID: number

      ID of the comment to get.

    Returns Promise<DocComment>

  • Get every comments from a doc.

    Parameters

    • channelID: string

      ID of the channel containing the doc.

    • docID: number

      ID of the doc the comment is in.

    Returns Promise<DocComment[]>

  • This method is used to get a list of "Channel" Doc.

    Parameters

    • channelID: string

      ID of a "Docs" channel.

    • Optional filter: GetDocsFilter

      Object to filter the output.

    Returns Promise<Doc[]>

  • This method is used to get a specific forum thread comment.

    Parameters

    • channelID: string

      ID of a "Forums" channel.

    • threadID: number

      ID of a Forum thread.

    • commentID: number

      ID of a Forum thread comment.

    Returns Promise<ForumThreadComment>

  • Get a cached guild, returns undefined if not cached.

    Note: this method doesn't send a rest request, it only returns cached entities.

    Parameters

    • guildID: string

      The ID of the guild to get.

    Returns undefined | Guild

  • Get a guild role.

    Parameters

    • guildID: string

      ID of the guild where the role is.

    • roleID: number

      ID of the role to get.

    Returns Promise<GuildRole>

  • This method is used to get a specific list item.

    Parameters

    • channelID: string

      ID of a "List" channel.

    • itemID: string

      ID of a list item.

    Returns Promise<ListItem>

  • Returns the current max listener value for the EventEmitter which is either set by emitter.setMaxListeners(n) or defaults to defaultMaxListeners.

    Returns number

    Since

    v1.0.0

  • This method is used to get a specific guild member, if cached.

    Note: this method doesn't send a rest request, it only returns cached entities.

    Parameters

    • guildID: string

      The ID of the guild the member is in.

    • memberID: string

      The ID of the member to get.

    Returns undefined | Member

  • This method is used to get a list of cached guild member.

    Note: this method doesn't send a rest request, it only returns cached entities.

    Parameters

    • guildID: string

      ID of the guild to get members.

    Returns undefined | Member[]

  • Get a channel's message, if cached.

    Note: this method doesn't send a rest request, it only returns cached entities.

    Parameters

    • guildID: string

      ID of the guild.

    • channelID: string

      ID of the channel containing the message.

    • messageID: string

      ID of the message you'd like to get.

    Returns undefined | Message<TextChannel>

  • Get a user.

    Note: when getting the bot's user, only the information specific to 'User' will be returned. If you'd like to get the UserClient (the bot itself), use Client#user.

    Parameters

    • userID: string

      The ID of the user to get.

    Returns Promise<User>

  • Retrieve user's joined servers.

    Parameters

    • userID: string

      ID of the user. (@me can be used to select your instance)

    Returns Promise<Guild[]>

  • This method is used to get a specific webhook.

    Parameters

    • guildID: string

      ID of a guild.

    • webhookID: string

      ID of a webhook.

    Returns Promise<Webhook>

  • This method is used to get a list of Webhook.

    Parameters

    • guildID: string

      ID of a guild.

    • channelID: string

      ID of a channel.

    Returns Promise<Webhook[]>

  • Lock a forum thread.

    Parameters

    • channelID: string

      ID of a "Forums" channel.

    • threadID: number

      ID of a forum thread.

    Returns Promise<void>

  • Add a member to a group

    Parameters

    • groupID: string

      ID of a guild group.

    • memberID: string

      ID of a member.

    Returns Promise<void>

  • Add a role to a member

    Parameters

    • guildID: string

      ID of a guild.

    • memberID: string

      ID of a member.

    • roleID: number

      ID of a role.

    Returns Promise<void>

  • Remove a member from a group

    Parameters

    • groupID: string

      ID of a guild group.

    • memberID: string

      ID of a member.

    Returns Promise<void>

  • Remove a role from a member

    Parameters

    • guildID: string

      ID of a guild.

    • memberID: string

      ID of a member.

    • roleID: number

      ID of a role.

    Returns Promise<void>

  • Pin a forum thread.

    Parameters

    • channelID: string

      ID of a "Forums" channel.

    • threadID: number

      ID of a forum thread.

    Returns Promise<void>

  • Pin a message.

    Parameters

    • channelID: string

      ID of the channel where the message is.

    • messageID: string

      ID of the message to pin.

    Returns Promise<void>

  • Unban a guild member.

    Parameters

    • guildID: string

      ID of the guild the member was in.

    • memberID: string

      ID of the member to unban.

    Returns Promise<void>

  • Remove a member from a guild.

    Parameters

    • guildID: string

      The ID of the guild the member is in.

    • memberID: string

      The ID of the member to kick.

    Returns Promise<void>

  • Unarchive a channel.

    Parameters

    • channelID: string

      ID of the channel to unarchive.

    Returns Promise<void>

  • 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 toInfinity (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 Client

    Since

    v0.3.5

  • Set a member's xp using the built-in EXP system.

    Parameters

    • guildID: string

      ID of a guild.

    • memberID: string

      ID of a member.

    • amount: number

      Total amount of experience.

    Returns Promise<number>

  • Mark a list item as uncompleted.

    Parameters

    • channelID: string

      ID of a "Lists" channel.

    • itemID: string

      ID of a list item.

    Returns Promise<void>

  • Unlock a forum thread.

    Parameters

    • channelID: string

      ID of a "Forums" channel.

    • threadID: number

      ID of a forum thread.

    Returns Promise<void>

  • Unpin a forum thread.

    Parameters

    • channelID: string

      ID of a "Forums" channel.

    • threadID: number

      ID of a forum thread.

    Returns Promise<void>

  • Unpin a message.

    Parameters

    • channelID: string

      ID of the channel where the message is.

    • messageID: string

      ID of the message to unpin.

    Returns Promise<void>

  • Change a user's status, this includes the bot's one.

    Parameters

    • userID: string

      User ID (@me can be used).

    • options: PUTUserStatusBody

      Status options

    Returns Promise<void>

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

    const { getEventListeners, EventEmitter } = require('events');

    {
    const ee = new EventEmitter();
    const listener = () => console.log('Events are fun');
    ee.on('foo', listener);
    getEventListeners(ee, 'foo'); // [listener]
    }
    {
    const et = new EventTarget();
    const listener = () => console.log('Events are fun');
    et.addEventListener('foo', listener);
    getEventListeners(et, 'foo'); // [listener]
    }

    Parameters

    • emitter: EventEmitter | _DOMEventTarget
    • name: string | symbol

    Returns Function[]

    Since

    v15.2.0, v14.17.0

  • A class method that returns the number of listeners for the given eventNameregistered on the given emitter.

    const { EventEmitter, listenerCount } = require('events');
    const myEmitter = new EventEmitter();
    myEmitter.on('event', () => {});
    myEmitter.on('event', () => {});
    console.log(listenerCount(myEmitter, 'event'));
    // Prints: 2

    Parameters

    • emitter: EventEmitter

      The emitter to query

    • eventName: string | symbol

      The event name

    Returns number

    Since

    v0.9.12

    Deprecated

    Since v3.2.0 - Use listenerCount instead.

  • const { on, EventEmitter } = require('events');

    (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')) {
    // 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
    })();

    Returns 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:

    const { on, EventEmitter } = require('events');
    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());

    Parameters

    • emitter: EventEmitter
    • eventName: string

      The name of the event being listened for

    • Optional options: StaticEventEmitterOptions

    Returns AsyncIterableIterator<any>

    that iterates eventName events emitted by the emitter

    Since

    v13.6.0, v12.16.0

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

    const { once, EventEmitter } = require('events');

    async function run() {
    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.log('error happened', err);
    }
    }

    run();

    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:

    const { EventEmitter, once } = require('events');

    const ee = new EventEmitter();

    once(ee, 'error')
    .then(([err]) => console.log('ok', err.message))
    .catch((err) => console.log('error', err.message));

    ee.emit('error', new Error('boom'));

    // Prints: ok boom

    An AbortSignal can be used to cancel waiting for the event:

    const { EventEmitter, once } = require('events');

    const ee = new EventEmitter();
    const ac = new AbortController();

    async function foo(emitter, event, signal) {
    try {
    await once(emitter, event, { signal });
    console.log('event emitted!');
    } catch (error) {
    if (error.name === 'AbortError') {
    console.error('Waiting for the event was canceled!');
    } else {
    console.error('There was an error', error.message);
    }
    }
    }

    foo(ee, 'foo', ac.signal);
    ac.abort(); // Abort waiting for the event
    ee.emit('foo'); // Prints: Waiting for the event was canceled!

    Parameters

    • emitter: _NodeEventTarget
    • eventName: string | symbol
    • Optional options: StaticEventEmitterOptions

    Returns Promise<any[]>

    Since

    v11.13.0, v10.16.0

  • Parameters

    • emitter: _DOMEventTarget
    • eventName: string
    • Optional options: StaticEventEmitterOptions

    Returns Promise<any[]>

  • const {
    setMaxListeners,
    EventEmitter
    } = require('events');

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

    setMaxListeners(5, target, emitter);

    Parameters

    • Optional n: number

      A non-negative number. The maximum number of listeners per EventTarget event.

    • Rest ...eventTargets: (EventEmitter | _DOMEventTarget)[]

    Returns void

    Since

    v15.4.0