Bun

Node.js module

http

The 'node:http' module provides classes and methods to create HTTP servers and clients. It includes the IncomingMessage and ServerResponse classes for handling request/response lifecycles on the server side, and the ClientRequest and IncomingMessage classes for client-side HTTP interactions.

Works in Bun

Fully implemented. Note: Outgoing client request body is currently buffered instead of streamed.

  • class Agent

    An Agent is responsible for managing connection persistence and reuse for HTTP clients. It maintains a queue of pending requests for a given host and port, reusing a single socket connection for each until the queue is empty, at which time the socket is either destroyed or put into a pool where it is kept to be used again for requests to the same host and port. Whether it is destroyed or pooled depends on the keepAlive option.

    Pooled connections have TCP Keep-Alive enabled for them, but servers may still close idle connections, in which case they will be removed from the pool and a new connection will be made when a new HTTP request is made for that host and port. Servers may also refuse to allow multiple requests over the same connection, in which case the connection will have to be remade for every request and cannot be pooled. The Agent will still make the requests to that server, but each one will occur over a new connection.

    When a connection is closed by the client or the server, it is removed from the pool. Any unused sockets in the pool will be unrefed so as not to keep the Node.js process running when there are no outstanding requests. (see socket.unref()).

    It is good practice, to destroy() an Agent instance when it is no longer in use, because unused sockets consume OS resources.

    Sockets are removed from an agent when the socket emits either a 'close' event or an 'agentRemove' event. When intending to keep one HTTP request open for a long time without keeping it in the agent, something like the following may be done:

    http.get(options, (res) => {
      // Do stuff
    }).on('socket', (socket) => {
      socket.emit('agentRemove');
    });
    

    An agent may also be used for an individual request. By providing {agent: false} as an option to the http.get() or http.request() functions, a one-time use Agent with default options will be used for the client connection.

    agent:false:

    http.get({
      hostname: 'localhost',
      port: 80,
      path: '/',
      agent: false,  // Create a new agent just for this one request
    }, (res) => {
      // Do stuff with response
    });
    

    options in socket.connect() are also supported.

    To configure any of them, a custom Agent instance must be created.

    import http from 'node:http';
    const keepAliveAgent = new http.Agent({ keepAlive: true });
    options.agent = keepAliveAgent;
    http.request(options, onResponseCallback)
    
    • readonly freeSockets: ReadOnlyDict<Socket[]>

      An object which contains arrays of sockets currently awaiting use by the agent when keepAlive is enabled. Do not modify.

      Sockets in the freeSockets list will be automatically destroyed and removed from the array on 'timeout'.

    • maxFreeSockets: number

      By default set to 256. For agents with keepAlive enabled, this sets the maximum number of sockets that will be left open in the free state.

    • maxSockets: number

      By default set to Infinity. Determines how many concurrent sockets the agent can have open per origin. Origin is the returned value of agent.getName().

    • maxTotalSockets: number

      By default set to Infinity. Determines how many concurrent sockets the agent can have open. Unlike maxSockets, this parameter applies across all origins.

    • readonly requests: ReadOnlyDict<IncomingMessage[]>

      An object which contains queues of requests that have not yet been assigned to sockets. Do not modify.

    • readonly sockets: ReadOnlyDict<Socket[]>

      An object which contains arrays of sockets currently in use by the agent. Do not modify.

    • static captureRejections: boolean

      Value: boolean

      Change the default captureRejections option on all new EventEmitter objects.

    • readonly static captureRejectionSymbol: typeof captureRejectionSymbol

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

      See how to write a custom rejection handler.

    • static defaultMaxListeners: number

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

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

    • error: Error,
      event: string | symbol,
      ...args: AnyRest
      ): void;
    • eventName: string | symbol,
      listener: (...args: any[]) => void
      ): this;

      Alias for emitter.on(eventName, listener).

    • destroy(): void;

      Destroy any sockets that are currently in use by the agent.

      It is usually not necessary to do this. However, if using an agent with keepAlive enabled, then it is best to explicitly shut down the agent when it is no longer needed. Otherwise, sockets might stay open for quite a long time before the server terminates them.

    • emit<K>(
      eventName: string | symbol,
      ...args: AnyRest
      ): boolean;

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

      Returns true if the event had listeners, false otherwise.

      import { EventEmitter } from 'node:events';
      const myEmitter = new EventEmitter();
      
      // First listener
      myEmitter.on('event', function firstListener() {
        console.log('Helloooo! first listener');
      });
      // Second listener
      myEmitter.on('event', function secondListener(arg1, arg2) {
        console.log(`event with parameters ${arg1}, ${arg2} in second listener`);
      });
      // Third listener
      myEmitter.on('event', function thirdListener(...args) {
        const parameters = args.join(', ');
        console.log(`event with parameters ${parameters} in third listener`);
      });
      
      console.log(myEmitter.listeners('event'));
      
      myEmitter.emit('event', 1, 2, 3, 4, 5);
      
      // Prints:
      // [
      //   [Function: firstListener],
      //   [Function: secondListener],
      //   [Function: thirdListener]
      // ]
      // Helloooo! first listener
      // event with parameters 1, 2 in second listener
      // event with parameters 1, 2, 3, 4, 5 in third listener
      
    • eventNames(): string | symbol[];

      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) ]
      
    • getMaxListeners(): number;

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

    • eventName: string | symbol,
      listener?: Function
      ): number;

      Returns the number of listeners listening for the event named eventName. If listener is provided, it will return how many times the listener is found in the list of the listeners of the event.

      @param eventName

      The name of the event being listened for

      @param listener

      The event handler function

    • eventName: string | symbol
      ): Function[];

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

      server.on('connection', (stream) => {
        console.log('someone connected!');
      });
      console.log(util.inspect(server.listeners('connection')));
      // Prints: [ [Function] ]
      
    • off<K>(
      eventName: string | symbol,
      listener: (...args: any[]) => void
      ): this;

      Alias for emitter.removeListener().

    • on<K>(
      eventName: string | symbol,
      listener: (...args: any[]) => void
      ): this;

      Adds the listener function to the end of the listeners array for the event named eventName. No checks are made to see if the listener has already been added. Multiple calls passing the same combination of eventName and listener will result in the listener being added, and called, multiple times.

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

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

      By default, event listeners are invoked in the order they are added. The emitter.prependListener() method can be used as an alternative to add the event listener to the beginning of the listeners array.

      import { EventEmitter } from 'node:events';
      const myEE = new EventEmitter();
      myEE.on('foo', () => console.log('a'));
      myEE.prependListener('foo', () => console.log('b'));
      myEE.emit('foo');
      // Prints:
      //   b
      //   a
      
      @param eventName

      The name of the event.

      @param listener

      The callback function

    • once<K>(
      eventName: string | symbol,
      listener: (...args: any[]) => void
      ): this;

      Adds a one-time listener function for the event named eventName. The next time eventName is triggered, this listener is removed and then invoked.

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

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

      By default, event listeners are invoked in the order they are added. The emitter.prependOnceListener() method can be used as an alternative to add the event listener to the beginning of the listeners array.

      import { EventEmitter } from 'node:events';
      const myEE = new EventEmitter();
      myEE.once('foo', () => console.log('a'));
      myEE.prependOnceListener('foo', () => console.log('b'));
      myEE.emit('foo');
      // Prints:
      //   b
      //   a
      
      @param eventName

      The name of the event.

      @param listener

      The callback function

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

      Adds the listener function to the beginning of the listeners array for the event named eventName. No checks are made to see if the listener has already been added. Multiple calls passing the same combination of eventName and listener will result in the listener being added, and called, multiple times.

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

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

      @param eventName

      The name of the event.

      @param listener

      The callback function

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

      Adds a one-timelistener function for the event named eventName to the beginning of the listeners array. The next time eventName is triggered, this listener is removed, and then invoked.

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

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

      @param eventName

      The name of the event.

      @param listener

      The callback function

    • eventName: string | symbol
      ): Function[];

      Returns a copy of the array of listeners for the event named eventName, including any wrappers (such as those created by .once()).

      import { EventEmitter } from 'node:events';
      const emitter = new EventEmitter();
      emitter.once('log', () => console.log('log once'));
      
      // Returns a new Array with a function `onceWrapper` which has a property
      // `listener` which contains the original listener bound above
      const listeners = emitter.rawListeners('log');
      const logFnWrapper = listeners[0];
      
      // Logs "log once" to the console and does not unbind the `once` event
      logFnWrapper.listener();
      
      // Logs "log once" to the console and removes the listener
      logFnWrapper();
      
      emitter.on('log', () => console.log('log persistently'));
      // Will return a new Array with a single function bound by `.on()` above
      const newListeners = emitter.rawListeners('log');
      
      // Logs "log persistently" twice
      newListeners[0]();
      emitter.emit('log');
      
    • eventName?: string | symbol
      ): this;

      Removes all listeners, or those of the specified eventName.

      It is bad practice to remove listeners added elsewhere in the code, particularly when the EventEmitter instance was created by some other component or module (e.g. sockets or file streams).

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

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

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

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

      removeListener() will remove, at most, one instance of a listener from the listener array. If any single listener has been added multiple times to the listener array for the specified eventName, then removeListener() must be called multiple times to remove each instance.

      Once an event is emitted, all listeners attached to it at the time of emitting are called in order. This implies that any removeListener() or removeAllListeners() calls after emitting and before the last listener finishes execution will not remove them fromemit() in progress. Subsequent events behave as expected.

      import { EventEmitter } from 'node:events';
      class MyEmitter extends EventEmitter {}
      const myEmitter = new MyEmitter();
      
      const callbackA = () => {
        console.log('A');
        myEmitter.removeListener('event', callbackB);
      };
      
      const callbackB = () => {
        console.log('B');
      };
      
      myEmitter.on('event', callbackA);
      
      myEmitter.on('event', callbackB);
      
      // callbackA removes listener callbackB but it will still be called.
      // Internal listener array at time of emit [callbackA, callbackB]
      myEmitter.emit('event');
      // Prints:
      //   A
      //   B
      
      // callbackB is now removed.
      // Internal listener array [callbackA]
      myEmitter.emit('event');
      // Prints:
      //   A
      

      Because listeners are managed using an internal array, calling this will change the position indices of any listener registered after the listener being removed. This will not impact the order in which listeners are called, but it means that any copies of the listener array as returned by the emitter.listeners() method will need to be recreated.

      When a single function has been added as a handler multiple times for a single event (as in the example below), removeListener() will remove the most recently added instance. In the example the once('ping') listener is removed:

      import { EventEmitter } from 'node:events';
      const ee = new EventEmitter();
      
      function pong() {
        console.log('pong');
      }
      
      ee.on('ping', pong);
      ee.once('ping', pong);
      ee.removeListener('ping', pong);
      
      ee.emit('ping');
      ee.emit('ping');
      

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

    • n: number
      ): this;

      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.

    • signal: AbortSignal,
      resource: (event: Event) => void
      ): Disposable;

      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]();
        }
      }
      
      @returns

      Disposable that removes the abort listener.

    • emitter: EventEmitter<DefaultEventMap> | EventTarget,
      name: string | symbol
      ): Function[];

      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] ]
      }
      
    • emitter: EventEmitter<DefaultEventMap> | EventTarget
      ): number;

      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
      }
      
    • static on(
      emitter: EventEmitter,
      eventName: string | symbol,
      options?: StaticEventEmitterIteratorOptions
      ): AsyncIterator<any[]>;
      import { on, EventEmitter } from 'node:events';
      import process from 'node:process';
      
      const ee = new EventEmitter();
      
      // Emit later on
      process.nextTick(() => {
        ee.emit('foo', 'bar');
        ee.emit('foo', 42);
      });
      
      for await (const event of on(ee, 'foo')) {
        // The execution of this inner block is synchronous and it
        // processes one event at a time (even with await). Do not use
        // if concurrent execution is required.
        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:

      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 on
      process.nextTick(() => {
        ee.emit('foo', 'bar');
        ee.emit('foo', 42);
        ee.emit('close');
      });
      
      for await (const event of on(ee, 'foo', { close: ['close'] })) {
        console.log(event); // prints ['bar'] [42]
      }
      // the loop will exit after 'close' is emitted
      console.log('done'); // prints 'done'
      
      @returns

      An AsyncIterator that iterates eventName events emitted by the emitter

      static on(
      emitter: EventTarget,
      eventName: string,
      options?: StaticEventEmitterIteratorOptions
      ): AsyncIterator<any[]>;
      import { on, EventEmitter } from 'node:events';
      import process from 'node:process';
      
      const ee = new EventEmitter();
      
      // Emit later on
      process.nextTick(() => {
        ee.emit('foo', 'bar');
        ee.emit('foo', 42);
      });
      
      for await (const event of on(ee, 'foo')) {
        // The execution of this inner block is synchronous and it
        // processes one event at a time (even with await). Do not use
        // if concurrent execution is required.
        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:

      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 on
      process.nextTick(() => {
        ee.emit('foo', 'bar');
        ee.emit('foo', 42);
        ee.emit('close');
      });
      
      for await (const event of on(ee, 'foo', { close: ['close'] })) {
        console.log(event); // prints ['bar'] [42]
      }
      // the loop will exit after 'close' is emitted
      console.log('done'); // prints 'done'
      
      @returns

      An AsyncIterator that iterates eventName events emitted by the emitter

    • static once(
      emitter: EventEmitter,
      eventName: string | symbol,
      options?: StaticEventEmitterOptions
      ): Promise<any[]>;

      Creates a Promise that is fulfilled when the EventEmitter emits the given event or that is rejected if the EventEmitter emits 'error' while waiting. The Promise will resolve with an array of all the arguments emitted to the given event.

      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 boom
      

      An 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 event
      ee.emit('foo'); // Prints: Waiting for the event was canceled!
      
      static once(
      emitter: EventTarget,
      eventName: string,
      options?: StaticEventEmitterOptions
      ): Promise<any[]>;

      Creates a Promise that is fulfilled when the EventEmitter emits the given event or that is rejected if the EventEmitter emits 'error' while waiting. The Promise will resolve with an array of all the arguments emitted to the given event.

      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 boom
      

      An 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 event
      ee.emit('foo'); // Prints: Waiting for the event was canceled!
      
    • n?: number,
      ...eventTargets: EventEmitter<DefaultEventMap> | EventTarget[]
      ): void;
      import { setMaxListeners, EventEmitter } from 'node:events';
      
      const target = new EventTarget();
      const emitter = new EventEmitter();
      
      setMaxListeners(5, target, emitter);
      
      @param n

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

      @param eventTargets

      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.

  • class ClientRequest

    This object is created internally and returned from request. It represents an in-progress request whose header has already been queued. The header is still mutable using the setHeader(name, value), getHeader(name), removeHeader(name) API. The actual header will be sent along with the first data chunk or when calling request.end().

    To get the response, add a listener for 'response' to the request object. 'response' will be emitted from the request object when the response headers have been received. The 'response' event is executed with one argument which is an instance of IncomingMessage.

    During the 'response' event, one can add listeners to the response object; particularly to listen for the 'data' event.

    If no 'response' handler is added, then the response will be entirely discarded. However, if a 'response' event handler is added, then the data from the response object must be consumed, either by calling response.read() whenever there is a 'readable' event, or by adding a 'data' handler, or by calling the .resume() method. Until the data is consumed, the 'end' event will not fire. Also, until the data is read it will consume memory that can eventually lead to a 'process out of memory' error.

    For backward compatibility, res will only emit 'error' if there is an 'error' listener registered.

    Set Content-Length header to limit the response body size. If response.strictContentLength is set to true, mismatching the Content-Length header value will result in an Error being thrown, identified by code:``'ERR_HTTP_CONTENT_LENGTH_MISMATCH'.

    Content-Length value should be in bytes, not characters. Use Buffer.byteLength() to determine the length of the body in bytes.

    • readonly closed: boolean

      Is true after 'close' has been emitted.

    • destroyed: boolean

      Is true after writable.destroy() has been called.

    • readonly errored: null | Error

      Returns error if the stream has been destroyed with an error.

    • readonly headersSent: boolean

      Read-only. true if the headers were sent, otherwise false.

    • host: string

      The request host.

    • maxHeadersCount: number

      Limits maximum response headers count. If set to 0, no limit will be applied.

    • method: string

      The request method.

    • path: string

      The request path.

    • protocol: string

      The request protocol.

    • reusedSocket: boolean

      When sending request through a keep-alive enabled agent, the underlying socket might be reused. But if server closes connection at unfortunate time, client may run into a 'ECONNRESET' error.

      import http from 'node:http';
      
      // Server has a 5 seconds keep-alive timeout by default
      http
        .createServer((req, res) => {
          res.write('hello\n');
          res.end();
        })
        .listen(3000);
      
      setInterval(() => {
        // Adapting a keep-alive agent
        http.get('http://localhost:3000', { agent }, (res) => {
          res.on('data', (data) => {
            // Do nothing
          });
        });
      }, 5000); // Sending request on 5s interval so it's easy to hit idle timeout
      

      By marking a request whether it reused socket or not, we can do automatic error retry base on it.

      import http from 'node:http';
      const agent = new http.Agent({ keepAlive: true });
      
      function retriableRequest() {
        const req = http
          .get('http://localhost:3000', { agent }, (res) => {
            // ...
          })
          .on('error', (err) => {
            // Check if retry is needed
            if (req.reusedSocket &#x26;&#x26; err.code === 'ECONNRESET') {
              retriableRequest();
            }
          });
      }
      
      retriableRequest();
      
    • sendDate: boolean
    • readonly socket: null | Socket

      Reference to the underlying socket. Usually, users will not want to access this property.

      After calling outgoingMessage.end(), this property will be nulled.

    • readonly writable: boolean

      Is true if it is safe to call writable.write(), which means the stream has not been destroyed, errored, or ended.

    • readonly writableCorked: number

      Number of times writable.uncork() needs to be called in order to fully uncork the stream.

    • readonly writableEnded: boolean

      Is true after writable.end() has been called. This property does not indicate whether the data has been flushed, for this use writable.writableFinished instead.

    • readonly writableFinished: boolean

      Is set to true immediately before the 'finish' event is emitted.

    • readonly writableHighWaterMark: number

      Return the value of highWaterMark passed when creating this Writable.

    • readonly writableLength: number

      This property contains the number of bytes (or objects) in the queue ready to be written. The value provides introspection data regarding the status of the highWaterMark.

    • readonly writableNeedDrain: boolean

      Is true if the stream's buffer has been full and stream will emit 'drain'.

    • readonly writableObjectMode: boolean

      Getter for the property objectMode of a given Writable stream.

    • static captureRejections: boolean

      Value: boolean

      Change the default captureRejections option on all new EventEmitter objects.

    • readonly static captureRejectionSymbol: typeof captureRejectionSymbol

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

      See how to write a custom rejection handler.

    • static defaultMaxListeners: number

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

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

    • callback: (error?: null | Error) => void
      ): void;
    • error: null | Error,
      callback: (error?: null | Error) => void
      ): void;
    • callback: (error?: null | Error) => void
      ): void;
    • chunk: any,
      encoding: BufferEncoding,
      callback: (error?: null | Error) => void
      ): void;
    • chunks: { chunk: any; encoding: BufferEncoding }[],
      callback: (error?: null | Error) => void
      ): void;
    • error: Error,
      event: string | symbol,
      ...args: AnyRest
      ): void;
    • headers: OutgoingHttpHeaders | readonly [string, string][]
      ): void;

      Adds HTTP trailers (headers but at the end of the message) to the message.

      Trailers will only be emitted if the message is chunked encoded. If not, the trailers will be silently discarded.

      HTTP requires the Trailer header to be sent to emit trailers, with a list of header field names in its value, e.g.

      message.writeHead(200, { 'Content-Type': 'text/plain',
                               'Trailer': 'Content-MD5' });
      message.write(fileData);
      message.addTrailers({ 'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667' });
      message.end();
      

      Attempting to set a header field name or value that contains invalid characters will result in a TypeError being thrown.

    • name: string,
      value: string | readonly string[]
      ): this;

      Append a single header value to the header object.

      If the value is an array, this is equivalent to calling this method multiple times.

      If there were no previous values for the header, this is equivalent to calling outgoingMessage.setHeader(name, value).

      Depending of the value of options.uniqueHeaders when the client request or the server were created, this will end up in the header being sent multiple times or a single time with values joined using ; .

      @param name

      Header name

      @param value

      Header value

    • compose<T extends ReadableStream>(
      stream: ComposeFnParam | T | Iterable<T, any, any> | AsyncIterable<T, any, any>,
      options?: { signal: AbortSignal }
      ): T;
    • cork(): void;

      The writable.cork() method forces all written data to be buffered in memory. The buffered data will be flushed when either the uncork or end methods are called.

      The primary intent of writable.cork() is to accommodate a situation in which several small chunks are written to the stream in rapid succession. Instead of immediately forwarding them to the underlying destination, writable.cork() buffers all the chunks until writable.uncork() is called, which will pass them all to writable._writev(), if present. This prevents a head-of-line blocking situation where data is being buffered while waiting for the first small chunk to be processed. However, use of writable.cork() without implementing writable._writev() may have an adverse effect on throughput.

      See also: writable.uncork(), writable._writev().

    • error?: Error
      ): this;

      Destroy the stream. Optionally emit an 'error' event, and emit a 'close' event (unless emitClose is set to false). After this call, the writable stream has ended and subsequent calls to write() or end() will result in an ERR_STREAM_DESTROYED error. This is a destructive and immediate way to destroy a stream. Previous calls to write() may not have drained, and may trigger an ERR_STREAM_DESTROYED error. Use end() instead of destroy if data should flush before close, or wait for the 'drain' event before destroying the stream.

      Once destroy() has been called any further calls will be a no-op and no further errors except from _destroy() may be emitted as 'error'.

      Implementors should not override this method, but instead implement writable._destroy().

      @param error

      Optional, an error to emit with 'error' event.

    • event: 'close'
      ): boolean;

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

      Returns true if the event had listeners, false otherwise.

      import { EventEmitter } from 'node:events';
      const myEmitter = new EventEmitter();
      
      // First listener
      myEmitter.on('event', function firstListener() {
        console.log('Helloooo! first listener');
      });
      // Second listener
      myEmitter.on('event', function secondListener(arg1, arg2) {
        console.log(`event with parameters ${arg1}, ${arg2} in second listener`);
      });
      // Third listener
      myEmitter.on('event', function thirdListener(...args) {
        const parameters = args.join(', ');
        console.log(`event with parameters ${parameters} in third listener`);
      });
      
      console.log(myEmitter.listeners('event'));
      
      myEmitter.emit('event', 1, 2, 3, 4, 5);
      
      // Prints:
      // [
      //   [Function: firstListener],
      //   [Function: secondListener],
      //   [Function: thirdListener]
      // ]
      // Helloooo! first listener
      // event with parameters 1, 2 in second listener
      // event with parameters 1, 2, 3, 4, 5 in third listener
      
      event: 'drain'
      ): boolean;
      event: 'error',
      err: Error
      ): boolean;
      event: 'finish'
      ): boolean;
      event: 'pipe',
      ): boolean;
      event: 'unpipe',
      ): boolean;
      event: string | symbol,
      ...args: any[]
      ): boolean;
    • cb?: () => void
      ): this;

      Calling the writable.end() method signals that no more data will be written to the Writable. The optional chunk and encoding arguments allow one final additional chunk of data to be written immediately before closing the stream.

      Calling the write method after calling end will raise an error.

      // Write 'hello, ' and then end with 'world!'.
      import fs from 'node:fs';
      const file = fs.createWriteStream('example.txt');
      file.write('hello, ');
      file.end('world!');
      // Writing more now is not allowed!
      
      chunk: any,
      cb?: () => void
      ): this;

      Calling the writable.end() method signals that no more data will be written to the Writable. The optional chunk and encoding arguments allow one final additional chunk of data to be written immediately before closing the stream.

      Calling the write method after calling end will raise an error.

      // Write 'hello, ' and then end with 'world!'.
      import fs from 'node:fs';
      const file = fs.createWriteStream('example.txt');
      file.write('hello, ');
      file.end('world!');
      // Writing more now is not allowed!
      
      @param chunk

      Optional data to write. For streams not operating in object mode, chunk must be a {string}, {Buffer}, {TypedArray} or {DataView}. For object mode streams, chunk may be any JavaScript value other than null.

      chunk: any,
      encoding: BufferEncoding,
      cb?: () => void
      ): this;

      Calling the writable.end() method signals that no more data will be written to the Writable. The optional chunk and encoding arguments allow one final additional chunk of data to be written immediately before closing the stream.

      Calling the write method after calling end will raise an error.

      // Write 'hello, ' and then end with 'world!'.
      import fs from 'node:fs';
      const file = fs.createWriteStream('example.txt');
      file.write('hello, ');
      file.end('world!');
      // Writing more now is not allowed!
      
      @param chunk

      Optional data to write. For streams not operating in object mode, chunk must be a {string}, {Buffer}, {TypedArray} or {DataView}. For object mode streams, chunk may be any JavaScript value other than null.

      @param encoding

      The encoding if chunk is a string

    • eventNames(): string | symbol[];

      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) ]
      
    • flushHeaders(): void;

      Flushes the message headers.

      For efficiency reason, Node.js normally buffers the message headers until outgoingMessage.end() is called or the first chunk of message data is written. It then tries to pack the headers and data into a single TCP packet.

      It is usually desired (it saves a TCP round-trip), but not when the first data is not sent until possibly much later. outgoingMessage.flushHeaders() bypasses the optimization and kickstarts the message.

    • name: string
      ): undefined | string | number | string[];

      Gets the value of the HTTP header with the given name. If that header is not set, the returned value will be undefined.

      @param name

      Name of header

    • getHeaderNames(): string[];

      Returns an array containing the unique names of the current outgoing headers. All names are lowercase.

    • Returns a shallow copy of the current outgoing headers. Since a shallow copy is used, array values may be mutated without additional calls to various header-related HTTP module methods. The keys of the returned object are the header names and the values are the respective header values. All header names are lowercase.

      The object returned by the outgoingMessage.getHeaders() method does not prototypically inherit from the JavaScript Object. This means that typical Object methods such as obj.toString(), obj.hasOwnProperty(), and others are not defined and will not work.

      outgoingMessage.setHeader('Foo', 'bar');
      outgoingMessage.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);
      
      const headers = outgoingMessage.getHeaders();
      // headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] }
      
    • getMaxListeners(): number;

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

    • getRawHeaderNames(): string[];

      Returns an array containing the unique names of the current outgoing raw headers. Header names are returned with their exact casing being set.

      request.setHeader('Foo', 'bar');
      request.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);
      
      const headerNames = request.getRawHeaderNames();
      // headerNames === ['Foo', 'Set-Cookie']
      
    • name: string
      ): boolean;

      Returns true if the header identified by name is currently set in the outgoing headers. The header name is case-insensitive.

      const hasContentType = outgoingMessage.hasHeader('content-type');
      
    • eventName: string | symbol,
      listener?: Function
      ): number;

      Returns the number of listeners listening for the event named eventName. If listener is provided, it will return how many times the listener is found in the list of the listeners of the event.

      @param eventName

      The name of the event being listened for

      @param listener

      The event handler function

    • eventName: string | symbol
      ): Function[];

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

      server.on('connection', (stream) => {
        console.log('someone connected!');
      });
      console.log(util.inspect(server.listeners('connection')));
      // Prints: [ [Function] ]
      
    • off<K>(
      eventName: string | symbol,
      listener: (...args: any[]) => void
      ): this;

      Alias for emitter.removeListener().

    • socket: Socket
      ): void;
    • pipe<T extends WritableStream>(
      destination: T,
      options?: { end: boolean }
      ): T;
    • eventName: string | symbol
      ): Function[];

      Returns a copy of the array of listeners for the event named eventName, including any wrappers (such as those created by .once()).

      import { EventEmitter } from 'node:events';
      const emitter = new EventEmitter();
      emitter.once('log', () => console.log('log once'));
      
      // Returns a new Array with a function `onceWrapper` which has a property
      // `listener` which contains the original listener bound above
      const listeners = emitter.rawListeners('log');
      const logFnWrapper = listeners[0];
      
      // Logs "log once" to the console and does not unbind the `once` event
      logFnWrapper.listener();
      
      // Logs "log once" to the console and removes the listener
      logFnWrapper();
      
      emitter.on('log', () => console.log('log persistently'));
      // Will return a new Array with a single function bound by `.on()` above
      const newListeners = emitter.rawListeners('log');
      
      // Logs "log persistently" twice
      newListeners[0]();
      emitter.emit('log');
      
    • eventName?: string | symbol
      ): this;

      Removes all listeners, or those of the specified eventName.

      It is bad practice to remove listeners added elsewhere in the code, particularly when the EventEmitter instance was created by some other component or module (e.g. sockets or file streams).

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

    • name: string
      ): void;

      Removes a header that is queued for implicit sending.

      outgoingMessage.removeHeader('Content-Encoding');
      
      @param name

      Header name

    • event: 'close',
      listener: () => void
      ): this;

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

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

      removeListener() will remove, at most, one instance of a listener from the listener array. If any single listener has been added multiple times to the listener array for the specified eventName, then removeListener() must be called multiple times to remove each instance.

      Once an event is emitted, all listeners attached to it at the time of emitting are called in order. This implies that any removeListener() or removeAllListeners() calls after emitting and before the last listener finishes execution will not remove them fromemit() in progress. Subsequent events behave as expected.

      import { EventEmitter } from 'node:events';
      class MyEmitter extends EventEmitter {}
      const myEmitter = new MyEmitter();
      
      const callbackA = () => {
        console.log('A');
        myEmitter.removeListener('event', callbackB);
      };
      
      const callbackB = () => {
        console.log('B');
      };
      
      myEmitter.on('event', callbackA);
      
      myEmitter.on('event', callbackB);
      
      // callbackA removes listener callbackB but it will still be called.
      // Internal listener array at time of emit [callbackA, callbackB]
      myEmitter.emit('event');
      // Prints:
      //   A
      //   B
      
      // callbackB is now removed.
      // Internal listener array [callbackA]
      myEmitter.emit('event');
      // Prints:
      //   A
      

      Because listeners are managed using an internal array, calling this will change the position indices of any listener registered after the listener being removed. This will not impact the order in which listeners are called, but it means that any copies of the listener array as returned by the emitter.listeners() method will need to be recreated.

      When a single function has been added as a handler multiple times for a single event (as in the example below), removeListener() will remove the most recently added instance. In the example the once('ping') listener is removed:

      import { EventEmitter } from 'node:events';
      const ee = new EventEmitter();
      
      function pong() {
        console.log('pong');
      }
      
      ee.on('ping', pong);
      ee.once('ping', pong);
      ee.removeListener('ping', pong);
      
      ee.emit('ping');
      ee.emit('ping');
      

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

      event: 'drain',
      listener: () => void
      ): this;
      event: 'error',
      listener: (err: Error) => void
      ): this;
      event: 'finish',
      listener: () => void
      ): this;
      event: 'pipe',
      listener: (src: Readable) => void
      ): this;
      event: 'unpipe',
      listener: (src: Readable) => void
      ): this;
      event: string | symbol,
      listener: (...args: any[]) => void
      ): this;
    • encoding: BufferEncoding
      ): this;

      The writable.setDefaultEncoding() method sets the default encoding for a Writable stream.

      @param encoding

      The new default encoding

    • name: string,
      value: string | number | readonly string[]
      ): this;

      Sets a single header value. If the header already exists in the to-be-sent headers, its value will be replaced. Use an array of strings to send multiple headers with the same name.

      @param name

      Header name

      @param value

      Header value

    • headers: Headers | Map<string, string | number | readonly string[]>
      ): this;

      Sets multiple header values for implicit headers. headers must be an instance of Headers or Map, if a header already exists in the to-be-sent headers, its value will be replaced.

      const headers = new Headers({ foo: 'bar' });
      outgoingMessage.setHeaders(headers);
      

      or

      const headers = new Map([['foo', 'bar']]);
      outgoingMessage.setHeaders(headers);
      

      When headers have been set with outgoingMessage.setHeaders(), they will be merged with any headers passed to response.writeHead(), with the headers passed to response.writeHead() given precedence.

      // Returns content-type = text/plain
      const server = http.createServer((req, res) => {
        const headers = new Headers({ 'Content-Type': 'text/html' });
        res.setHeaders(headers);
        res.writeHead(200, { 'Content-Type': 'text/plain' });
        res.end('ok');
      });
      
    • n: number
      ): this;

      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.

    • noDelay?: boolean
      ): void;

      Once a socket is assigned to this request and is connected socket.setNoDelay() will be called.

    • enable?: boolean,
      initialDelay?: number
      ): void;

      Once a socket is assigned to this request and is connected socket.setKeepAlive() will be called.

    • timeout: number,
      callback?: () => void
      ): this;

      Once a socket is assigned to this request and is connected socket.setTimeout() will be called.

      @param timeout

      Milliseconds before a request times out.

      @param callback

      Optional function to be called when a timeout occurs. Same as binding to the 'timeout' event.

    • uncork(): void;

      The writable.uncork() method flushes all data buffered since cork was called.

      When using writable.cork() and writable.uncork() to manage the buffering of writes to a stream, defer calls to writable.uncork() using process.nextTick(). Doing so allows batching of all writable.write() calls that occur within a given Node.js event loop phase.

      stream.cork();
      stream.write('some ');
      stream.write('data ');
      process.nextTick(() => stream.uncork());
      

      If the writable.cork() method is called multiple times on a stream, the same number of calls to writable.uncork() must be called to flush the buffered data.

      stream.cork();
      stream.write('some ');
      stream.cork();
      stream.write('data ');
      process.nextTick(() => {
        stream.uncork();
        // The data will not be flushed until uncork() is called a second time.
        stream.uncork();
      });
      

      See also: writable.cork().

    • chunk: any,
      callback?: (error: undefined | null | Error) => void
      ): boolean;

      The writable.write() method writes some data to the stream, and calls the supplied callback once the data has been fully handled. If an error occurs, the callback will be called with the error as its first argument. The callback is called asynchronously and before 'error' is emitted.

      The return value is true if the internal buffer is less than the highWaterMark configured when the stream was created after admitting chunk. If false is returned, further attempts to write data to the stream should stop until the 'drain' event is emitted.

      While a stream is not draining, calls to write() will buffer chunk, and return false. Once all currently buffered chunks are drained (accepted for delivery by the operating system), the 'drain' event will be emitted. Once write() returns false, do not write more chunks until the 'drain' event is emitted. While calling write() on a stream that is not draining is allowed, Node.js will buffer all written chunks until maximum memory usage occurs, at which point it will abort unconditionally. Even before it aborts, high memory usage will cause poor garbage collector performance and high RSS (which is not typically released back to the system, even after the memory is no longer required). Since TCP sockets may never drain if the remote peer does not read the data, writing a socket that is not draining may lead to a remotely exploitable vulnerability.

      Writing data while the stream is not draining is particularly problematic for a Transform, because the Transform streams are paused by default until they are piped or a 'data' or 'readable' event handler is added.

      If the data to be written can be generated or fetched on demand, it is recommended to encapsulate the logic into a Readable and use pipe. However, if calling write() is preferred, it is possible to respect backpressure and avoid memory issues using the 'drain' event:

      function write(data, cb) {
        if (!stream.write(data)) {
          stream.once('drain', cb);
        } else {
          process.nextTick(cb);
        }
      }
      
      // Wait for cb to be called before doing any other write.
      write('hello', () => {
        console.log('Write completed, do more writes now.');
      });
      

      A Writable stream in object mode will always ignore the encoding argument.

      @param chunk

      Optional data to write. For streams not operating in object mode, chunk must be a {string}, {Buffer}, {TypedArray} or {DataView}. For object mode streams, chunk may be any JavaScript value other than null.

      @param callback

      Callback for when this chunk of data is flushed.

      @returns

      false if the stream wishes for the calling code to wait for the 'drain' event to be emitted before continuing to write additional data; otherwise true.

      chunk: any,
      encoding: BufferEncoding,
      callback?: (error: undefined | null | Error) => void
      ): boolean;

      The writable.write() method writes some data to the stream, and calls the supplied callback once the data has been fully handled. If an error occurs, the callback will be called with the error as its first argument. The callback is called asynchronously and before 'error' is emitted.

      The return value is true if the internal buffer is less than the highWaterMark configured when the stream was created after admitting chunk. If false is returned, further attempts to write data to the stream should stop until the 'drain' event is emitted.

      While a stream is not draining, calls to write() will buffer chunk, and return false. Once all currently buffered chunks are drained (accepted for delivery by the operating system), the 'drain' event will be emitted. Once write() returns false, do not write more chunks until the 'drain' event is emitted. While calling write() on a stream that is not draining is allowed, Node.js will buffer all written chunks until maximum memory usage occurs, at which point it will abort unconditionally. Even before it aborts, high memory usage will cause poor garbage collector performance and high RSS (which is not typically released back to the system, even after the memory is no longer required). Since TCP sockets may never drain if the remote peer does not read the data, writing a socket that is not draining may lead to a remotely exploitable vulnerability.

      Writing data while the stream is not draining is particularly problematic for a Transform, because the Transform streams are paused by default until they are piped or a 'data' or 'readable' event handler is added.

      If the data to be written can be generated or fetched on demand, it is recommended to encapsulate the logic into a Readable and use pipe. However, if calling write() is preferred, it is possible to respect backpressure and avoid memory issues using the 'drain' event:

      function write(data, cb) {
        if (!stream.write(data)) {
          stream.once('drain', cb);
        } else {
          process.nextTick(cb);
        }
      }
      
      // Wait for cb to be called before doing any other write.
      write('hello', () => {
        console.log('Write completed, do more writes now.');
      });
      

      A Writable stream in object mode will always ignore the encoding argument.

      @param chunk

      Optional data to write. For streams not operating in object mode, chunk must be a {string}, {Buffer}, {TypedArray} or {DataView}. For object mode streams, chunk may be any JavaScript value other than null.

      @param encoding

      The encoding, if chunk is a string.

      @param callback

      Callback for when this chunk of data is flushed.

      @returns

      false if the stream wishes for the calling code to wait for the 'drain' event to be emitted before continuing to write additional data; otherwise true.

    • signal: AbortSignal,
      resource: (event: Event) => void
      ): Disposable;

      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]();
        }
      }
      
      @returns

      Disposable that removes the abort listener.

    • static fromWeb(
      writableStream: WritableStream,
      options?: Pick<WritableOptions<Writable>, 'signal' | 'decodeStrings' | 'highWaterMark' | 'objectMode'>

      A utility method for creating a Writable from a web WritableStream.

    • emitter: EventEmitter<DefaultEventMap> | EventTarget,
      name: string | symbol
      ): Function[];

      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] ]
      }
      
    • emitter: EventEmitter<DefaultEventMap> | EventTarget
      ): number;

      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
      }
      
    • static on(
      emitter: EventEmitter,
      eventName: string | symbol,
      options?: StaticEventEmitterIteratorOptions
      ): AsyncIterator<any[]>;
      import { on, EventEmitter } from 'node:events';
      import process from 'node:process';
      
      const ee = new EventEmitter();
      
      // Emit later on
      process.nextTick(() => {
        ee.emit('foo', 'bar');
        ee.emit('foo', 42);
      });
      
      for await (const event of on(ee, 'foo')) {
        // The execution of this inner block is synchronous and it
        // processes one event at a time (even with await). Do not use
        // if concurrent execution is required.
        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:

      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 on
      process.nextTick(() => {
        ee.emit('foo', 'bar');
        ee.emit('foo', 42);
        ee.emit('close');
      });
      
      for await (const event of on(ee, 'foo', { close: ['close'] })) {
        console.log(event); // prints ['bar'] [42]
      }
      // the loop will exit after 'close' is emitted
      console.log('done'); // prints 'done'
      
      @returns

      An AsyncIterator that iterates eventName events emitted by the emitter

      static on(
      emitter: EventTarget,
      eventName: string,
      options?: StaticEventEmitterIteratorOptions
      ): AsyncIterator<any[]>;
      import { on, EventEmitter } from 'node:events';
      import process from 'node:process';
      
      const ee = new EventEmitter();
      
      // Emit later on
      process.nextTick(() => {
        ee.emit('foo', 'bar');
        ee.emit('foo', 42);
      });
      
      for await (const event of on(ee, 'foo')) {
        // The execution of this inner block is synchronous and it
        // processes one event at a time (even with await). Do not use
        // if concurrent execution is required.
        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:

      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 on
      process.nextTick(() => {
        ee.emit('foo', 'bar');
        ee.emit('foo', 42);
        ee.emit('close');
      });
      
      for await (const event of on(ee, 'foo', { close: ['close'] })) {
        console.log(event); // prints ['bar'] [42]
      }
      // the loop will exit after 'close' is emitted
      console.log('done'); // prints 'done'
      
      @returns

      An AsyncIterator that iterates eventName events emitted by the emitter

    • static once(
      emitter: EventEmitter,
      eventName: string | symbol,
      options?: StaticEventEmitterOptions
      ): Promise<any[]>;

      Creates a Promise that is fulfilled when the EventEmitter emits the given event or that is rejected if the EventEmitter emits 'error' while waiting. The Promise will resolve with an array of all the arguments emitted to the given event.

      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 boom
      

      An 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 event
      ee.emit('foo'); // Prints: Waiting for the event was canceled!
      
      static once(
      emitter: EventTarget,
      eventName: string,
      options?: StaticEventEmitterOptions
      ): Promise<any[]>;

      Creates a Promise that is fulfilled when the EventEmitter emits the given event or that is rejected if the EventEmitter emits 'error' while waiting. The Promise will resolve with an array of all the arguments emitted to the given event.

      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 boom
      

      An 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 event
      ee.emit('foo'); // Prints: Waiting for the event was canceled!
      
    • n?: number,
      ...eventTargets: EventEmitter<DefaultEventMap> | EventTarget[]
      ): void;
      import { setMaxListeners, EventEmitter } from 'node:events';
      
      const target = new EventTarget();
      const emitter = new EventEmitter();
      
      setMaxListeners(5, target, emitter);
      
      @param n

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

      @param eventTargets

      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.

    • static toWeb(
      streamWritable: Writable

      A utility method for creating a web WritableStream from a Writable.

  • class IncomingMessage

    An IncomingMessage object is created by Server or ClientRequest and passed as the first argument to the 'request' and 'response' event respectively. It may be used to access response status, headers, and data.

    Different from its socket value which is a subclass of stream.Duplex, the IncomingMessage itself extends stream.Readable and is created separately to parse and emit the incoming HTTP headers and payload, as the underlying socket may be reused multiple times in case of keep-alive.

    • readonly closed: boolean

      Is true after 'close' has been emitted.

    • complete: boolean

      The message.complete property will be true if a complete HTTP message has been received and successfully parsed.

      This property is particularly useful as a means of determining if a client or server fully transmitted a message before a connection was terminated:

      const req = http.request({
        host: '127.0.0.1',
        port: 8080,
        method: 'POST',
      }, (res) => {
        res.resume();
        res.on('end', () => {
          if (!res.complete)
            console.error(
              'The connection was terminated while the message was still being sent');
        });
      });
      
    • destroyed: boolean

      Is true after readable.destroy() has been called.

    • readonly errored: null | Error

      Returns error if the stream has been destroyed with an error.

    • headers: IncomingHttpHeaders

      The request/response headers object.

      Key-value pairs of header names and values. Header names are lower-cased.

      // Prints something like:
      //
      // { 'user-agent': 'curl/7.22.0',
      //   host: '127.0.0.1:8000',
      //   accept: '*' }
      console.log(request.headers);
      

      Duplicates in raw headers are handled in the following ways, depending on the header name:

      • Duplicates of age, authorization, content-length, content-type, etag, expires, from, host, if-modified-since, if-unmodified-since, last-modified, location, max-forwards, proxy-authorization, referer, retry-after, server, or user-agent are discarded. To allow duplicate values of the headers listed above to be joined, use the option joinDuplicateHeaders in request and createServer. See RFC 9110 Section 5.3 for more information.
      • set-cookie is always an array. Duplicates are added to the array.
      • For duplicate cookie headers, the values are joined together with ; .
      • For all other headers, the values are joined together with , .
    • headersDistinct: Dict<string[]>

      Similar to message.headers, but there is no join logic and the values are always arrays of strings, even for headers received just once.

      // Prints something like:
      //
      // { 'user-agent': ['curl/7.22.0'],
      //   host: ['127.0.0.1:8000'],
      //   accept: ['*'] }
      console.log(request.headersDistinct);
      
    • httpVersion: string

      In case of server request, the HTTP version sent by the client. In the case of client response, the HTTP version of the connected-to server. Probably either '1.1' or '1.0'.

      Also message.httpVersionMajor is the first integer and message.httpVersionMinor is the second.

    • method?: string

      Only valid for request obtained from Server.

      The request method as a string. Read only. Examples: 'GET', 'DELETE'.

    • rawHeaders: string[]

      The raw request/response headers list exactly as they were received.

      The keys and values are in the same list. It is not a list of tuples. So, the even-numbered offsets are key values, and the odd-numbered offsets are the associated values.

      Header names are not lowercased, and duplicates are not merged.

      // Prints something like:
      //
      // [ 'user-agent',
      //   'this is invalid because there can be only one',
      //   'User-Agent',
      //   'curl/7.22.0',
      //   'Host',
      //   '127.0.0.1:8000',
      //   'ACCEPT',
      //   '*' ]
      console.log(request.rawHeaders);
      
    • rawTrailers: string[]

      The raw request/response trailer keys and values exactly as they were received. Only populated at the 'end' event.

    • readable: boolean

      Is true if it is safe to call read, which means the stream has not been destroyed or emitted 'error' or 'end'.

    • readonly readableAborted: boolean

      Returns whether the stream was destroyed or errored before emitting 'end'.

    • readonly readableDidRead: boolean

      Returns whether 'data' has been emitted.

    • readonly readableEncoding: null | BufferEncoding

      Getter for the property encoding of a given Readable stream. The encoding property can be set using the setEncoding method.

    • readonly readableEnded: boolean

      Becomes true when 'end' event is emitted.

    • readonly readableFlowing: null | boolean

      This property reflects the current state of a Readable stream as described in the Three states section.

    • readonly readableHighWaterMark: number

      Returns the value of highWaterMark passed when creating this Readable.

    • readonly readableLength: number

      This property contains the number of bytes (or objects) in the queue ready to be read. The value provides introspection data regarding the status of the highWaterMark.

    • readonly readableObjectMode: boolean

      Getter for the property objectMode of a given Readable stream.

    • socket: Socket

      The net.Socket object associated with the connection.

      With HTTPS support, use request.socket.getPeerCertificate() to obtain the client's authentication details.

      This property is guaranteed to be an instance of the net.Socket class, a subclass of stream.Duplex, unless the user specified a socket type other than net.Socket or internally nulled.

    • statusCode?: number

      Only valid for response obtained from ClientRequest.

      The 3-digit HTTP response status code. E.G. 404.

    • statusMessage?: string

      Only valid for response obtained from ClientRequest.

      The HTTP response status message (reason phrase). E.G. OK or Internal Server Error.

    • trailers: Dict<string>

      The request/response trailers object. Only populated at the 'end' event.

    • trailersDistinct: Dict<string[]>

      Similar to message.trailers, but there is no join logic and the values are always arrays of strings, even for headers received just once. Only populated at the 'end' event.

    • url?: string

      Only valid for request obtained from Server.

      Request URL string. This contains only the URL that is present in the actual HTTP request. Take the following request:

      GET /status?name=ryan HTTP/1.1
      Accept: text/plain
      

      To parse the URL into its parts:

      new URL(`http://${process.env.HOST ?? 'localhost'}${request.url}`);
      

      When request.url is '/status?name=ryan' and process.env.HOST is undefined:

      $ node
      > new URL(`http://${process.env.HOST ?? 'localhost'}${request.url}`);
      URL {
        href: 'http://localhost/status?name=ryan',
        origin: 'http://localhost',
        protocol: 'http:',
        username: '',
        password: '',
        host: 'localhost',
        hostname: 'localhost',
        port: '',
        pathname: '/status',
        search: '?name=ryan',
        searchParams: URLSearchParams { 'name' => 'ryan' },
        hash: ''
      }
      

      Ensure that you set process.env.HOST to the server's host name, or consider replacing this part entirely. If using req.headers.host, ensure proper validation is used, as clients may specify a custom Host header.

    • static captureRejections: boolean

      Value: boolean

      Change the default captureRejections option on all new EventEmitter objects.

    • readonly static captureRejectionSymbol: typeof captureRejectionSymbol

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

      See how to write a custom rejection handler.

    • static defaultMaxListeners: number

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

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

    • callback: (error?: null | Error) => void
      ): void;
    • error: null | Error,
      callback: (error?: null | Error) => void
      ): void;
    • size: number
      ): void;
    • [Symbol.asyncDispose](): Promise<void>;

      Calls readable.destroy() with an AbortError and returns a promise that fulfills when the stream is finished.

    • [Symbol.asyncIterator](): AsyncIterator<any>;
    • error: Error,
      event: string | symbol,
      ...args: AnyRest
      ): void;
    • event: 'close',
      listener: () => void
      ): this;

      Event emitter The defined events on documents including:

      1. close
      2. data
      3. end
      4. error
      5. pause
      6. readable
      7. resume
      event: 'data',
      listener: (chunk: any) => void
      ): this;

      Event emitter The defined events on documents including:

      1. close
      2. data
      3. end
      4. error
      5. pause
      6. readable
      7. resume
      event: 'end',
      listener: () => void
      ): this;

      Event emitter The defined events on documents including:

      1. close
      2. data
      3. end
      4. error
      5. pause
      6. readable
      7. resume
      event: 'error',
      listener: (err: Error) => void
      ): this;

      Event emitter The defined events on documents including:

      1. close
      2. data
      3. end
      4. error
      5. pause
      6. readable
      7. resume
      event: 'pause',
      listener: () => void
      ): this;

      Event emitter The defined events on documents including:

      1. close
      2. data
      3. end
      4. error
      5. pause
      6. readable
      7. resume
      event: 'readable',
      listener: () => void
      ): this;

      Event emitter The defined events on documents including:

      1. close
      2. data
      3. end
      4. error
      5. pause
      6. readable
      7. resume
      event: 'resume',
      listener: () => void
      ): this;

      Event emitter The defined events on documents including:

      1. close
      2. data
      3. end
      4. error
      5. pause
      6. readable
      7. resume
      event: string | symbol,
      listener: (...args: any[]) => void
      ): this;

      Event emitter The defined events on documents including:

      1. close
      2. data
      3. end
      4. error
      5. pause
      6. readable
      7. resume
    • options?: Pick<ArrayOptions, 'signal'>

      This method returns a new stream with chunks of the underlying stream paired with a counter in the form [index, chunk]. The first index value is 0 and it increases by 1 for each chunk produced.

      @returns

      a stream of indexed pairs.

    • compose<T extends ReadableStream>(
      stream: ComposeFnParam | T | Iterable<T, any, any> | AsyncIterable<T, any, any>,
      options?: { signal: AbortSignal }
      ): T;
    • error?: Error
      ): this;

      Calls destroy() on the socket that received the IncomingMessage. If error is provided, an 'error' event is emitted on the socket and error is passed as an argument to any listeners on the event.

    • limit: number,
      options?: Pick<ArrayOptions, 'signal'>

      This method returns a new stream with the first limit chunks dropped from the start.

      @param limit

      the number of chunks to drop from the readable.

      @returns

      a stream with limit chunks dropped from the start.

    • event: 'close'
      ): boolean;

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

      Returns true if the event had listeners, false otherwise.

      import { EventEmitter } from 'node:events';
      const myEmitter = new EventEmitter();
      
      // First listener
      myEmitter.on('event', function firstListener() {
        console.log('Helloooo! first listener');
      });
      // Second listener
      myEmitter.on('event', function secondListener(arg1, arg2) {
        console.log(`event with parameters ${arg1}, ${arg2} in second listener`);
      });
      // Third listener
      myEmitter.on('event', function thirdListener(...args) {
        const parameters = args.join(', ');
        console.log(`event with parameters ${parameters} in third listener`);
      });
      
      console.log(myEmitter.listeners('event'));
      
      myEmitter.emit('event', 1, 2, 3, 4, 5);
      
      // Prints:
      // [
      //   [Function: firstListener],
      //   [Function: secondListener],
      //   [Function: thirdListener]
      // ]
      // Helloooo! first listener
      // event with parameters 1, 2 in second listener
      // event with parameters 1, 2, 3, 4, 5 in third listener
      
      event: 'data',
      chunk: any
      ): boolean;
      event: 'end'
      ): boolean;
      event: 'error',
      err: Error
      ): boolean;
      event: 'pause'
      ): boolean;
      event: 'readable'
      ): boolean;
      event: 'resume'
      ): boolean;
      event: string | symbol,
      ...args: any[]
      ): boolean;
    • eventNames(): string | symbol[];

      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) ]
      
    • fn: (data: any, options?: Pick<ArrayOptions, 'signal'>) => boolean | Promise<boolean>,
      options?: ArrayOptions
      ): Promise<boolean>;

      This method is similar to Array.prototype.every and calls fn on each chunk in the stream to check if all awaited return values are truthy value for fn. Once an fn call on a chunk awaited return value is falsy, the stream is destroyed and the promise is fulfilled with false. If all of the fn calls on the chunks return a truthy value, the promise is fulfilled with true.

      @param fn

      a function to call on each chunk of the stream. Async or not.

      @returns

      a promise evaluating to true if fn returned a truthy value for every one of the chunks.

    • fn: (data: any, options?: Pick<ArrayOptions, 'signal'>) => boolean | Promise<boolean>,
      options?: ArrayOptions

      This method allows filtering the stream. For each chunk in the stream the fn function will be called and if it returns a truthy value, the chunk will be passed to the result stream. If the fn function returns a promise - that promise will be awaited.

      @param fn

      a function to filter chunks from the stream. Async or not.

      @returns

      a stream filtered with the predicate fn.

    • find<T>(
      fn: (data: any, options?: Pick<ArrayOptions, 'signal'>) => data is T,
      options?: ArrayOptions
      ): Promise<undefined | T>;

      This method is similar to Array.prototype.find and calls fn on each chunk in the stream to find a chunk with a truthy value for fn. Once an fn call's awaited return value is truthy, the stream is destroyed and the promise is fulfilled with value for which fn returned a truthy value. If all of the fn calls on the chunks return a falsy value, the promise is fulfilled with undefined.

      @param fn

      a function to call on each chunk of the stream. Async or not.

      @returns

      a promise evaluating to the first chunk for which fn evaluated with a truthy value, or undefined if no element was found.

      fn: (data: any, options?: Pick<ArrayOptions, 'signal'>) => boolean | Promise<boolean>,
      options?: ArrayOptions
      ): Promise<any>;

      This method is similar to Array.prototype.find and calls fn on each chunk in the stream to find a chunk with a truthy value for fn. Once an fn call's awaited return value is truthy, the stream is destroyed and the promise is fulfilled with value for which fn returned a truthy value. If all of the fn calls on the chunks return a falsy value, the promise is fulfilled with undefined.

      @param fn

      a function to call on each chunk of the stream. Async or not.

      @returns

      a promise evaluating to the first chunk for which fn evaluated with a truthy value, or undefined if no element was found.

    • fn: (data: any, options?: Pick<ArrayOptions, 'signal'>) => any,
      options?: ArrayOptions

      This method returns a new stream by applying the given callback to each chunk of the stream and then flattening the result.

      It is possible to return a stream or another iterable or async iterable from fn and the result streams will be merged (flattened) into the returned stream.

      @param fn

      a function to map over every chunk in the stream. May be async. May be a stream or generator.

      @returns

      a stream flat-mapped with the function fn.

    • fn: (data: any, options?: Pick<ArrayOptions, 'signal'>) => void | Promise<void>,
      options?: ArrayOptions
      ): Promise<void>;

      This method allows iterating a stream. For each chunk in the stream the fn function will be called. If the fn function returns a promise - that promise will be awaited.

      This method is different from for await...of loops in that it can optionally process chunks concurrently. In addition, a forEach iteration can only be stopped by having passed a signal option and aborting the related AbortController while for await...of can be stopped with break or return. In either case the stream will be destroyed.

      This method is different from listening to the 'data' event in that it uses the readable event in the underlying machinary and can limit the number of concurrent fn calls.

      @param fn

      a function to call on each chunk of the stream. Async or not.

      @returns

      a promise for when the stream has finished.

    • getMaxListeners(): number;

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

    • isPaused(): boolean;

      The readable.isPaused() method returns the current operating state of the Readable. This is used primarily by the mechanism that underlies the readable.pipe() method. In most typical cases, there will be no reason to use this method directly.

      const readable = new stream.Readable();
      
      readable.isPaused(); // === false
      readable.pause();
      readable.isPaused(); // === true
      readable.resume();
      readable.isPaused(); // === false
      
    • options?: { destroyOnReturn: boolean }
      ): AsyncIterator<any>;

      The iterator created by this method gives users the option to cancel the destruction of the stream if the for await...of loop is exited by return, break, or throw, or if the iterator should destroy the stream if the stream emitted an error during iteration.

    • eventName: string | symbol,
      listener?: Function
      ): number;

      Returns the number of listeners listening for the event named eventName. If listener is provided, it will return how many times the listener is found in the list of the listeners of the event.

      @param eventName

      The name of the event being listened for

      @param listener

      The event handler function

    • eventName: string | symbol
      ): Function[];

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

      server.on('connection', (stream) => {
        console.log('someone connected!');
      });
      console.log(util.inspect(server.listeners('connection')));
      // Prints: [ [Function] ]
      
    • fn: (data: any, options?: Pick<ArrayOptions, 'signal'>) => any,
      options?: ArrayOptions

      This method allows mapping over the stream. The fn function will be called for every chunk in the stream. If the fn function returns a promise - that promise will be awaited before being passed to the result stream.

      @param fn

      a function to map over every chunk in the stream. Async or not.

      @returns

      a stream mapped with the function fn.

    • off<K>(
      eventName: string | symbol,
      listener: (...args: any[]) => void
      ): this;

      Alias for emitter.removeListener().

    • event: 'close',
      listener: () => void
      ): this;

      Adds the listener function to the end of the listeners array for the event named eventName. No checks are made to see if the listener has already been added. Multiple calls passing the same combination of eventName and listener will result in the listener being added, and called, multiple times.

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

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

      By default, event listeners are invoked in the order they are added. The emitter.prependListener() method can be used as an alternative to add the event listener to the beginning of the listeners array.

      import { EventEmitter } from 'node:events';
      const myEE = new EventEmitter();
      myEE.on('foo', () => console.log('a'));
      myEE.prependListener('foo', () => console.log('b'));
      myEE.emit('foo');
      // Prints:
      //   b
      //   a
      
      @param listener

      The callback function

      event: 'data',
      listener: (chunk: any) => void
      ): this;
      event: 'end',
      listener: () => void
      ): this;
      event: 'error',
      listener: (err: Error) => void
      ): this;
      event: 'pause',
      listener: () => void
      ): this;
      event: 'readable',
      listener: () => void
      ): this;
      event: 'resume',
      listener: () => void
      ): this;
      event: string | symbol,
      listener: (...args: any[]) => void
      ): this;
    • event: 'close',
      listener: () => void
      ): this;

      Adds a one-time listener function for the event named eventName. The next time eventName is triggered, this listener is removed and then invoked.

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

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

      By default, event listeners are invoked in the order they are added. The emitter.prependOnceListener() method can be used as an alternative to add the event listener to the beginning of the listeners array.

      import { EventEmitter } from 'node:events';
      const myEE = new EventEmitter();
      myEE.once('foo', () => console.log('a'));
      myEE.prependOnceListener('foo', () => console.log('b'));
      myEE.emit('foo');
      // Prints:
      //   b
      //   a
      
      @param listener

      The callback function

      event: 'data',
      listener: (chunk: any) => void
      ): this;
      event: 'end',
      listener: () => void
      ): this;
      event: 'error',
      listener: (err: Error) => void
      ): this;
      event: 'pause',
      listener: () => void
      ): this;
      event: 'readable',
      listener: () => void
      ): this;
      event: 'resume',
      listener: () => void
      ): this;
      event: string | symbol,
      listener: (...args: any[]) => void
      ): this;
    • pause(): this;

      The readable.pause() method will cause a stream in flowing mode to stop emitting 'data' events, switching out of flowing mode. Any data that becomes available will remain in the internal buffer.

      const readable = getReadableStreamSomehow();
      readable.on('data', (chunk) => {
        console.log(`Received ${chunk.length} bytes of data.`);
        readable.pause();
        console.log('There will be no additional data for 1 second.');
        setTimeout(() => {
          console.log('Now data will start flowing again.');
          readable.resume();
        }, 1000);
      });
      

      The readable.pause() method has no effect if there is a 'readable' event listener.

    • pipe<T extends WritableStream>(
      destination: T,
      options?: { end: boolean }
      ): T;
    • event: 'close',
      listener: () => void
      ): this;

      Adds the listener function to the beginning of the listeners array for the event named eventName. No checks are made to see if the listener has already been added. Multiple calls passing the same combination of eventName and listener will result in the listener being added, and called, multiple times.

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

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

      @param listener

      The callback function

      event: 'data',
      listener: (chunk: any) => void
      ): this;
      event: 'end',
      listener: () => void
      ): this;
      event: 'error',
      listener: (err: Error) => void
      ): this;
      event: 'pause',
      listener: () => void
      ): this;
      event: 'readable',
      listener: () => void
      ): this;
      event: 'resume',
      listener: () => void
      ): this;
      event: string | symbol,
      listener: (...args: any[]) => void
      ): this;
    • event: 'close',
      listener: () => void
      ): this;

      Adds a one-timelistener function for the event named eventName to the beginning of the listeners array. The next time eventName is triggered, this listener is removed, and then invoked.

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

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

      @param listener

      The callback function

      event: 'data',
      listener: (chunk: any) => void
      ): this;
      event: 'end',
      listener: () => void
      ): this;
      event: 'error',
      listener: (err: Error) => void
      ): this;
      event: 'pause',
      listener: () => void
      ): this;
      event: 'readable',
      listener: () => void
      ): this;
      event: 'resume',
      listener: () => void
      ): this;
      event: string | symbol,
      listener: (...args: any[]) => void
      ): this;
    • chunk: any,
      encoding?: BufferEncoding
      ): boolean;
    • eventName: string | symbol
      ): Function[];

      Returns a copy of the array of listeners for the event named eventName, including any wrappers (such as those created by .once()).

      import { EventEmitter } from 'node:events';
      const emitter = new EventEmitter();
      emitter.once('log', () => console.log('log once'));
      
      // Returns a new Array with a function `onceWrapper` which has a property
      // `listener` which contains the original listener bound above
      const listeners = emitter.rawListeners('log');
      const logFnWrapper = listeners[0];
      
      // Logs "log once" to the console and does not unbind the `once` event
      logFnWrapper.listener();
      
      // Logs "log once" to the console and removes the listener
      logFnWrapper();
      
      emitter.on('log', () => console.log('log persistently'));
      // Will return a new Array with a single function bound by `.on()` above
      const newListeners = emitter.rawListeners('log');
      
      // Logs "log persistently" twice
      newListeners[0]();
      emitter.emit('log');
      
    • size?: number
      ): any;

      The readable.read() method reads data out of the internal buffer and returns it. If no data is available to be read, null is returned. By default, the data is returned as a Buffer object unless an encoding has been specified using the readable.setEncoding() method or the stream is operating in object mode.

      The optional size argument specifies a specific number of bytes to read. If size bytes are not available to be read, null will be returned unless the stream has ended, in which case all of the data remaining in the internal buffer will be returned.

      If the size argument is not specified, all of the data contained in the internal buffer will be returned.

      The size argument must be less than or equal to 1 GiB.

      The readable.read() method should only be called on Readable streams operating in paused mode. In flowing mode, readable.read() is called automatically until the internal buffer is fully drained.

      const readable = getReadableStreamSomehow();
      
      // 'readable' may be triggered multiple times as data is buffered in
      readable.on('readable', () => {
        let chunk;
        console.log('Stream is readable (new data received in buffer)');
        // Use a loop to make sure we read all currently available data
        while (null !== (chunk = readable.read())) {
          console.log(`Read ${chunk.length} bytes of data...`);
        }
      });
      
      // 'end' will be triggered once when there is no more data available
      readable.on('end', () => {
        console.log('Reached end of stream.');
      });
      

      Each call to readable.read() returns a chunk of data, or null. The chunks are not concatenated. A while loop is necessary to consume all data currently in the buffer. When reading a large file .read() may return null, having consumed all buffered content so far, but there is still more data to come not yet buffered. In this case a new 'readable' event will be emitted when there is more data in the buffer. Finally the 'end' event will be emitted when there is no more data to come.

      Therefore to read a file's whole contents from a readable, it is necessary to collect chunks across multiple 'readable' events:

      const chunks = [];
      
      readable.on('readable', () => {
        let chunk;
        while (null !== (chunk = readable.read())) {
          chunks.push(chunk);
        }
      });
      
      readable.on('end', () => {
        const content = chunks.join('');
      });
      

      A Readable stream in object mode will always return a single item from a call to readable.read(size), regardless of the value of the size argument.

      If the readable.read() method returns a chunk of data, a 'data' event will also be emitted.

      Calling read after the 'end' event has been emitted will return null. No runtime error will be raised.

      @param size

      Optional argument to specify how much data to read.

    • reduce<T = any>(
      fn: (previous: any, data: any, options?: Pick<ArrayOptions, 'signal'>) => T,
      initial?: undefined,
      options?: Pick<ArrayOptions, 'signal'>
      ): Promise<T>;

      This method calls fn on each chunk of the stream in order, passing it the result from the calculation on the previous element. It returns a promise for the final value of the reduction.

      If no initial value is supplied the first chunk of the stream is used as the initial value. If the stream is empty, the promise is rejected with a TypeError with the ERR_INVALID_ARGS code property.

      The reducer function iterates the stream element-by-element which means that there is no concurrency parameter or parallelism. To perform a reduce concurrently, you can extract the async function to readable.map method.

      @param fn

      a reducer function to call over every chunk in the stream. Async or not.

      @param initial

      the initial value to use in the reduction.

      @returns

      a promise for the final value of the reduction.

      reduce<T = any>(
      fn: (previous: T, data: any, options?: Pick<ArrayOptions, 'signal'>) => T,
      initial: T,
      options?: Pick<ArrayOptions, 'signal'>
      ): Promise<T>;

      This method calls fn on each chunk of the stream in order, passing it the result from the calculation on the previous element. It returns a promise for the final value of the reduction.

      If no initial value is supplied the first chunk of the stream is used as the initial value. If the stream is empty, the promise is rejected with a TypeError with the ERR_INVALID_ARGS code property.

      The reducer function iterates the stream element-by-element which means that there is no concurrency parameter or parallelism. To perform a reduce concurrently, you can extract the async function to readable.map method.

      @param fn

      a reducer function to call over every chunk in the stream. Async or not.

      @param initial

      the initial value to use in the reduction.

      @returns

      a promise for the final value of the reduction.

    • eventName?: string | symbol
      ): this;

      Removes all listeners, or those of the specified eventName.

      It is bad practice to remove listeners added elsewhere in the code, particularly when the EventEmitter instance was created by some other component or module (e.g. sockets or file streams).

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

    • event: 'close',
      listener: () => void
      ): this;

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

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

      removeListener() will remove, at most, one instance of a listener from the listener array. If any single listener has been added multiple times to the listener array for the specified eventName, then removeListener() must be called multiple times to remove each instance.

      Once an event is emitted, all listeners attached to it at the time of emitting are called in order. This implies that any removeListener() or removeAllListeners() calls after emitting and before the last listener finishes execution will not remove them fromemit() in progress. Subsequent events behave as expected.

      import { EventEmitter } from 'node:events';
      class MyEmitter extends EventEmitter {}
      const myEmitter = new MyEmitter();
      
      const callbackA = () => {
        console.log('A');
        myEmitter.removeListener('event', callbackB);
      };
      
      const callbackB = () => {
        console.log('B');
      };
      
      myEmitter.on('event', callbackA);
      
      myEmitter.on('event', callbackB);
      
      // callbackA removes listener callbackB but it will still be called.
      // Internal listener array at time of emit [callbackA, callbackB]
      myEmitter.emit('event');
      // Prints:
      //   A
      //   B
      
      // callbackB is now removed.
      // Internal listener array [callbackA]
      myEmitter.emit('event');
      // Prints:
      //   A
      

      Because listeners are managed using an internal array, calling this will change the position indices of any listener registered after the listener being removed. This will not impact the order in which listeners are called, but it means that any copies of the listener array as returned by the emitter.listeners() method will need to be recreated.

      When a single function has been added as a handler multiple times for a single event (as in the example below), removeListener() will remove the most recently added instance. In the example the once('ping') listener is removed:

      import { EventEmitter } from 'node:events';
      const ee = new EventEmitter();
      
      function pong() {
        console.log('pong');
      }
      
      ee.on('ping', pong);
      ee.once('ping', pong);
      ee.removeListener('ping', pong);
      
      ee.emit('ping');
      ee.emit('ping');
      

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

      event: 'data',
      listener: (chunk: any) => void
      ): this;
      event: 'end',
      listener: () => void
      ): this;
      event: 'error',
      listener: (err: Error) => void
      ): this;
      event: 'pause',
      listener: () => void
      ): this;
      event: 'readable',
      listener: () => void
      ): this;
      event: 'resume',
      listener: () => void
      ): this;
      event: string | symbol,
      listener: (...args: any[]) => void
      ): this;
    • resume(): this;

      The readable.resume() method causes an explicitly paused Readable stream to resume emitting 'data' events, switching the stream into flowing mode.

      The readable.resume() method can be used to fully consume the data from a stream without actually processing any of that data:

      getReadableStreamSomehow()
        .resume()
        .on('end', () => {
          console.log('Reached the end, but did not read anything.');
        });
      

      The readable.resume() method has no effect if there is a 'readable' event listener.

    • encoding: BufferEncoding
      ): this;

      The readable.setEncoding() method sets the character encoding for data read from the Readable stream.

      By default, no encoding is assigned and stream data will be returned as Buffer objects. Setting an encoding causes the stream data to be returned as strings of the specified encoding rather than as Buffer objects. For instance, calling readable.setEncoding('utf8') will cause the output data to be interpreted as UTF-8 data, and passed as strings. Calling readable.setEncoding('hex') will cause the data to be encoded in hexadecimal string format.

      The Readable stream will properly handle multi-byte characters delivered through the stream that would otherwise become improperly decoded if simply pulled from the stream as Buffer objects.

      const readable = getReadableStreamSomehow();
      readable.setEncoding('utf8');
      readable.on('data', (chunk) => {
        assert.equal(typeof chunk, 'string');
        console.log('Got %d characters of string data:', chunk.length);
      });
      
      @param encoding

      The encoding to use.

    • n: number
      ): this;

      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.

    • msecs: number,
      callback?: () => void
      ): this;

      Calls message.socket.setTimeout(msecs, callback).

    • fn: (data: any, options?: Pick<ArrayOptions, 'signal'>) => boolean | Promise<boolean>,
      options?: ArrayOptions
      ): Promise<boolean>;

      This method is similar to Array.prototype.some and calls fn on each chunk in the stream until the awaited return value is true (or any truthy value). Once an fn call on a chunk awaited return value is truthy, the stream is destroyed and the promise is fulfilled with true. If none of the fn calls on the chunks return a truthy value, the promise is fulfilled with false.

      @param fn

      a function to call on each chunk of the stream. Async or not.

      @returns

      a promise evaluating to true if fn returned a truthy value for at least one of the chunks.

    • limit: number,
      options?: Pick<ArrayOptions, 'signal'>

      This method returns a new stream with the first limit chunks.

      @param limit

      the number of chunks to take from the readable.

      @returns

      a stream with limit chunks taken.

    • options?: Pick<ArrayOptions, 'signal'>
      ): Promise<any[]>;

      This method allows easily obtaining the contents of a stream.

      As this method reads the entire stream into memory, it negates the benefits of streams. It's intended for interoperability and convenience, not as the primary way to consume streams.

      @returns

      a promise containing an array with the contents of the stream.

    • destination?: WritableStream
      ): this;

      The readable.unpipe() method detaches a Writable stream previously attached using the pipe method.

      If the destination is not specified, then all pipes are detached.

      If the destination is specified, but no pipe is set up for it, then the method does nothing.

      import fs from 'node:fs';
      const readable = getReadableStreamSomehow();
      const writable = fs.createWriteStream('file.txt');
      // All the data from readable goes into 'file.txt',
      // but only for the first second.
      readable.pipe(writable);
      setTimeout(() => {
        console.log('Stop writing to file.txt.');
        readable.unpipe(writable);
        console.log('Manually close the file stream.');
        writable.end();
      }, 1000);
      
      @param destination

      Optional specific stream to unpipe

    • chunk: any,
      encoding?: BufferEncoding
      ): void;

      Passing chunk as null signals the end of the stream (EOF) and behaves the same as readable.push(null), after which no more data can be written. The EOF signal is put at the end of the buffer and any buffered data will still be flushed.

      The readable.unshift() method pushes a chunk of data back into the internal buffer. This is useful in certain situations where a stream is being consumed by code that needs to "un-consume" some amount of data that it has optimistically pulled out of the source, so that the data can be passed on to some other party.

      The stream.unshift(chunk) method cannot be called after the 'end' event has been emitted or a runtime error will be thrown.

      Developers using stream.unshift() often should consider switching to use of a Transform stream instead. See the API for stream implementers section for more information.

      // Pull off a header delimited by \n\n.
      // Use unshift() if we get too much.
      // Call the callback with (error, header, stream).
      import { StringDecoder } from 'node:string_decoder';
      function parseHeader(stream, callback) {
        stream.on('error', callback);
        stream.on('readable', onReadable);
        const decoder = new StringDecoder('utf8');
        let header = '';
        function onReadable() {
          let chunk;
          while (null !== (chunk = stream.read())) {
            const str = decoder.write(chunk);
            if (str.includes('\n\n')) {
              // Found the header boundary.
              const split = str.split(/\n\n/);
              header += split.shift();
              const remaining = split.join('\n\n');
              const buf = Buffer.from(remaining, 'utf8');
              stream.removeListener('error', callback);
              // Remove the 'readable' listener before unshifting.
              stream.removeListener('readable', onReadable);
              if (buf.length)
                stream.unshift(buf);
              // Now the body of the message can be read from the stream.
              callback(null, header, stream);
              return;
            }
            // Still reading the header.
            header += str;
          }
        }
      }
      

      Unlike push, stream.unshift(chunk) will not end the reading process by resetting the internal reading state of the stream. This can cause unexpected results if readable.unshift() is called during a read (i.e. from within a _read implementation on a custom stream). Following the call to readable.unshift() with an immediate push will reset the reading state appropriately, however it is best to simply avoid calling readable.unshift() while in the process of performing a read.

      @param chunk

      Chunk of data to unshift onto the read queue. For streams not operating in object mode, chunk must be a {string}, {Buffer}, {TypedArray}, {DataView} or null. For object mode streams, chunk may be any JavaScript value.

      @param encoding

      Encoding of string chunks. Must be a valid Buffer encoding, such as 'utf8' or 'ascii'.

    • stream: ReadableStream
      ): this;

      Prior to Node.js 0.10, streams did not implement the entire node:stream module API as it is currently defined. (See Compatibility for more information.)

      When using an older Node.js library that emits 'data' events and has a pause method that is advisory only, the readable.wrap() method can be used to create a Readable stream that uses the old stream as its data source.

      It will rarely be necessary to use readable.wrap() but the method has been provided as a convenience for interacting with older Node.js applications and libraries.

      import { OldReader } from './old-api-module.js';
      import { Readable } from 'node:stream';
      const oreader = new OldReader();
      const myReader = new Readable().wrap(oreader);
      
      myReader.on('readable', () => {
        myReader.read(); // etc.
      });
      
      @param stream

      An "old style" readable stream

    • signal: AbortSignal,
      resource: (event: Event) => void
      ): Disposable;

      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]();
        }
      }
      
      @returns

      Disposable that removes the abort listener.

    • static from(
      iterable: Iterable<any, any, any> | AsyncIterable<any, any, any>,

      A utility method for creating Readable Streams out of iterators.

      @param iterable

      Object implementing the Symbol.asyncIterator or Symbol.iterator iterable protocol. Emits an 'error' event if a null value is passed.

      @param options

      Options provided to new stream.Readable([options]). By default, Readable.from() will set options.objectMode to true, unless this is explicitly opted out by setting options.objectMode to false.

    • static fromWeb(
      readableStream: ReadableStream,
      options?: Pick<ReadableOptions<Readable>, 'signal' | 'encoding' | 'highWaterMark' | 'objectMode'>

      A utility method for creating a Readable from a web ReadableStream.

    • emitter: EventEmitter<DefaultEventMap> | EventTarget,
      name: string | symbol
      ): Function[];

      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] ]
      }
      
    • emitter: EventEmitter<DefaultEventMap> | EventTarget
      ): number;

      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
      }
      
    • static isDisturbed(
      stream: Readable | ReadableStream
      ): boolean;

      Returns whether the stream has been read from or cancelled.

    • static on(
      emitter: EventEmitter,
      eventName: string | symbol,
      options?: StaticEventEmitterIteratorOptions
      ): AsyncIterator<any[]>;
      import { on, EventEmitter } from 'node:events';
      import process from 'node:process';
      
      const ee = new EventEmitter();
      
      // Emit later on
      process.nextTick(() => {
        ee.emit('foo', 'bar');
        ee.emit('foo', 42);
      });
      
      for await (const event of on(ee, 'foo')) {
        // The execution of this inner block is synchronous and it
        // processes one event at a time (even with await). Do not use
        // if concurrent execution is required.
        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:

      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 on
      process.nextTick(() => {
        ee.emit('foo', 'bar');
        ee.emit('foo', 42);
        ee.emit('close');
      });
      
      for await (const event of on(ee, 'foo', { close: ['close'] })) {
        console.log(event); // prints ['bar'] [42]
      }
      // the loop will exit after 'close' is emitted
      console.log('done'); // prints 'done'
      
      @returns

      An AsyncIterator that iterates eventName events emitted by the emitter

      static on(
      emitter: EventTarget,
      eventName: string,
      options?: StaticEventEmitterIteratorOptions
      ): AsyncIterator<any[]>;
      import { on, EventEmitter } from 'node:events';
      import process from 'node:process';
      
      const ee = new EventEmitter();
      
      // Emit later on
      process.nextTick(() => {
        ee.emit('foo', 'bar');
        ee.emit('foo', 42);
      });
      
      for await (const event of on(ee, 'foo')) {
        // The execution of this inner block is synchronous and it
        // processes one event at a time (even with await). Do not use
        // if concurrent execution is required.
        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:

      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 on
      process.nextTick(() => {
        ee.emit('foo', 'bar');
        ee.emit('foo', 42);
        ee.emit('close');
      });
      
      for await (const event of on(ee, 'foo', { close: ['close'] })) {
        console.log(event); // prints ['bar'] [42]
      }
      // the loop will exit after 'close' is emitted
      console.log('done'); // prints 'done'
      
      @returns

      An AsyncIterator that iterates eventName events emitted by the emitter

    • static once(
      emitter: EventEmitter,
      eventName: string | symbol,
      options?: StaticEventEmitterOptions
      ): Promise<any[]>;

      Creates a Promise that is fulfilled when the EventEmitter emits the given event or that is rejected if the EventEmitter emits 'error' while waiting. The Promise will resolve with an array of all the arguments emitted to the given event.

      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 boom
      

      An 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 event
      ee.emit('foo'); // Prints: Waiting for the event was canceled!
      
      static once(
      emitter: EventTarget,
      eventName: string,
      options?: StaticEventEmitterOptions
      ): Promise<any[]>;

      Creates a Promise that is fulfilled when the EventEmitter emits the given event or that is rejected if the EventEmitter emits 'error' while waiting. The Promise will resolve with an array of all the arguments emitted to the given event.

      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 boom
      

      An 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 event
      ee.emit('foo'); // Prints: Waiting for the event was canceled!
      
    • n?: number,
      ...eventTargets: EventEmitter<DefaultEventMap> | EventTarget[]
      ): void;
      import { setMaxListeners, EventEmitter } from 'node:events';
      
      const target = new EventTarget();
      const emitter = new EventEmitter();
      
      setMaxListeners(5, target, emitter);
      
      @param n

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

      @param eventTargets

      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.

    • static toWeb(
      streamReadable: Readable,
      options?: { strategy: QueuingStrategy<any> }

      A utility method for creating a web ReadableStream from a Readable.

  • class OutgoingMessage<Request extends IncomingMessage = IncomingMessage>

    This class serves as the parent class of ClientRequest and ServerResponse. It is an abstract outgoing message from the perspective of the participants of an HTTP transaction.

    • readonly closed: boolean

      Is true after 'close' has been emitted.

    • destroyed: boolean

      Is true after writable.destroy() has been called.

    • readonly errored: null | Error

      Returns error if the stream has been destroyed with an error.

    • readonly headersSent: boolean

      Read-only. true if the headers were sent, otherwise false.

    • readonly req: Request
    • sendDate: boolean
    • readonly socket: null | Socket

      Reference to the underlying socket. Usually, users will not want to access this property.

      After calling outgoingMessage.end(), this property will be nulled.

    • readonly writable: boolean

      Is true if it is safe to call writable.write(), which means the stream has not been destroyed, errored, or ended.

    • readonly writableCorked: number

      Number of times writable.uncork() needs to be called in order to fully uncork the stream.

    • readonly writableEnded: boolean

      Is true after writable.end() has been called. This property does not indicate whether the data has been flushed, for this use writable.writableFinished instead.

    • readonly writableFinished: boolean

      Is set to true immediately before the 'finish' event is emitted.

    • readonly writableHighWaterMark: number

      Return the value of highWaterMark passed when creating this Writable.

    • readonly writableLength: number

      This property contains the number of bytes (or objects) in the queue ready to be written. The value provides introspection data regarding the status of the highWaterMark.

    • readonly writableNeedDrain: boolean

      Is true if the stream's buffer has been full and stream will emit 'drain'.

    • readonly writableObjectMode: boolean

      Getter for the property objectMode of a given Writable stream.

    • static captureRejections: boolean

      Value: boolean

      Change the default captureRejections option on all new EventEmitter objects.

    • readonly static captureRejectionSymbol: typeof captureRejectionSymbol

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

      See how to write a custom rejection handler.

    • static defaultMaxListeners: number

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

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

    • callback: (error?: null | Error) => void
      ): void;
    • error: null | Error,
      callback: (error?: null | Error) => void
      ): void;
    • callback: (error?: null | Error) => void
      ): void;
    • chunk: any,
      encoding: BufferEncoding,
      callback: (error?: null | Error) => void
      ): void;
    • chunks: { chunk: any; encoding: BufferEncoding }[],
      callback: (error?: null | Error) => void
      ): void;
    • error: Error,
      event: string | symbol,
      ...args: AnyRest
      ): void;
    • event: 'close',
      listener: () => void
      ): this;

      Event emitter The defined events on documents including:

      1. close
      2. drain
      3. error
      4. finish
      5. pipe
      6. unpipe
      event: 'drain',
      listener: () => void
      ): this;

      Event emitter The defined events on documents including:

      1. close
      2. drain
      3. error
      4. finish
      5. pipe
      6. unpipe
      event: 'error',
      listener: (err: Error) => void
      ): this;

      Event emitter The defined events on documents including:

      1. close
      2. drain
      3. error
      4. finish
      5. pipe
      6. unpipe
      event: 'finish',
      listener: () => void
      ): this;

      Event emitter The defined events on documents including:

      1. close
      2. drain
      3. error
      4. finish
      5. pipe
      6. unpipe
      event: 'pipe',
      listener: (src: Readable) => void
      ): this;

      Event emitter The defined events on documents including:

      1. close
      2. drain
      3. error
      4. finish
      5. pipe
      6. unpipe
      event: 'unpipe',
      listener: (src: Readable) => void
      ): this;

      Event emitter The defined events on documents including:

      1. close
      2. drain
      3. error
      4. finish
      5. pipe
      6. unpipe
      event: string | symbol,
      listener: (...args: any[]) => void
      ): this;

      Event emitter The defined events on documents including:

      1. close
      2. drain
      3. error
      4. finish
      5. pipe
      6. unpipe
    • headers: OutgoingHttpHeaders | readonly [string, string][]
      ): void;

      Adds HTTP trailers (headers but at the end of the message) to the message.

      Trailers will only be emitted if the message is chunked encoded. If not, the trailers will be silently discarded.

      HTTP requires the Trailer header to be sent to emit trailers, with a list of header field names in its value, e.g.

      message.writeHead(200, { 'Content-Type': 'text/plain',
                               'Trailer': 'Content-MD5' });
      message.write(fileData);
      message.addTrailers({ 'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667' });
      message.end();
      

      Attempting to set a header field name or value that contains invalid characters will result in a TypeError being thrown.

    • name: string,
      value: string | readonly string[]
      ): this;

      Append a single header value to the header object.

      If the value is an array, this is equivalent to calling this method multiple times.

      If there were no previous values for the header, this is equivalent to calling outgoingMessage.setHeader(name, value).

      Depending of the value of options.uniqueHeaders when the client request or the server were created, this will end up in the header being sent multiple times or a single time with values joined using ; .

      @param name

      Header name

      @param value

      Header value

    • compose<T extends ReadableStream>(
      stream: ComposeFnParam | T | Iterable<T, any, any> | AsyncIterable<T, any, any>,
      options?: { signal: AbortSignal }
      ): T;
    • cork(): void;

      The writable.cork() method forces all written data to be buffered in memory. The buffered data will be flushed when either the uncork or end methods are called.

      The primary intent of writable.cork() is to accommodate a situation in which several small chunks are written to the stream in rapid succession. Instead of immediately forwarding them to the underlying destination, writable.cork() buffers all the chunks until writable.uncork() is called, which will pass them all to writable._writev(), if present. This prevents a head-of-line blocking situation where data is being buffered while waiting for the first small chunk to be processed. However, use of writable.cork() without implementing writable._writev() may have an adverse effect on throughput.

      See also: writable.uncork(), writable._writev().

    • error?: Error
      ): this;

      Destroy the stream. Optionally emit an 'error' event, and emit a 'close' event (unless emitClose is set to false). After this call, the writable stream has ended and subsequent calls to write() or end() will result in an ERR_STREAM_DESTROYED error. This is a destructive and immediate way to destroy a stream. Previous calls to write() may not have drained, and may trigger an ERR_STREAM_DESTROYED error. Use end() instead of destroy if data should flush before close, or wait for the 'drain' event before destroying the stream.

      Once destroy() has been called any further calls will be a no-op and no further errors except from _destroy() may be emitted as 'error'.

      Implementors should not override this method, but instead implement writable._destroy().

      @param error

      Optional, an error to emit with 'error' event.

    • event: 'close'
      ): boolean;

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

      Returns true if the event had listeners, false otherwise.

      import { EventEmitter } from 'node:events';
      const myEmitter = new EventEmitter();
      
      // First listener
      myEmitter.on('event', function firstListener() {
        console.log('Helloooo! first listener');
      });
      // Second listener
      myEmitter.on('event', function secondListener(arg1, arg2) {
        console.log(`event with parameters ${arg1}, ${arg2} in second listener`);
      });
      // Third listener
      myEmitter.on('event', function thirdListener(...args) {
        const parameters = args.join(', ');
        console.log(`event with parameters ${parameters} in third listener`);
      });
      
      console.log(myEmitter.listeners('event'));
      
      myEmitter.emit('event', 1, 2, 3, 4, 5);
      
      // Prints:
      // [
      //   [Function: firstListener],
      //   [Function: secondListener],
      //   [Function: thirdListener]
      // ]
      // Helloooo! first listener
      // event with parameters 1, 2 in second listener
      // event with parameters 1, 2, 3, 4, 5 in third listener
      
      event: 'drain'
      ): boolean;
      event: 'error',
      err: Error
      ): boolean;
      event: 'finish'
      ): boolean;
      event: 'pipe',
      ): boolean;
      event: 'unpipe',
      ): boolean;
      event: string | symbol,
      ...args: any[]
      ): boolean;
    • cb?: () => void
      ): this;

      Calling the writable.end() method signals that no more data will be written to the Writable. The optional chunk and encoding arguments allow one final additional chunk of data to be written immediately before closing the stream.

      Calling the write method after calling end will raise an error.

      // Write 'hello, ' and then end with 'world!'.
      import fs from 'node:fs';
      const file = fs.createWriteStream('example.txt');
      file.write('hello, ');
      file.end('world!');
      // Writing more now is not allowed!
      
      chunk: any,
      cb?: () => void
      ): this;

      Calling the writable.end() method signals that no more data will be written to the Writable. The optional chunk and encoding arguments allow one final additional chunk of data to be written immediately before closing the stream.

      Calling the write method after calling end will raise an error.

      // Write 'hello, ' and then end with 'world!'.
      import fs from 'node:fs';
      const file = fs.createWriteStream('example.txt');
      file.write('hello, ');
      file.end('world!');
      // Writing more now is not allowed!
      
      @param chunk

      Optional data to write. For streams not operating in object mode, chunk must be a {string}, {Buffer}, {TypedArray} or {DataView}. For object mode streams, chunk may be any JavaScript value other than null.

      chunk: any,
      encoding: BufferEncoding,
      cb?: () => void
      ): this;

      Calling the writable.end() method signals that no more data will be written to the Writable. The optional chunk and encoding arguments allow one final additional chunk of data to be written immediately before closing the stream.

      Calling the write method after calling end will raise an error.

      // Write 'hello, ' and then end with 'world!'.
      import fs from 'node:fs';
      const file = fs.createWriteStream('example.txt');
      file.write('hello, ');
      file.end('world!');
      // Writing more now is not allowed!
      
      @param chunk

      Optional data to write. For streams not operating in object mode, chunk must be a {string}, {Buffer}, {TypedArray} or {DataView}. For object mode streams, chunk may be any JavaScript value other than null.

      @param encoding

      The encoding if chunk is a string

    • eventNames(): string | symbol[];

      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) ]
      
    • flushHeaders(): void;

      Flushes the message headers.

      For efficiency reason, Node.js normally buffers the message headers until outgoingMessage.end() is called or the first chunk of message data is written. It then tries to pack the headers and data into a single TCP packet.

      It is usually desired (it saves a TCP round-trip), but not when the first data is not sent until possibly much later. outgoingMessage.flushHeaders() bypasses the optimization and kickstarts the message.

    • name: string
      ): undefined | string | number | string[];

      Gets the value of the HTTP header with the given name. If that header is not set, the returned value will be undefined.

      @param name

      Name of header

    • getHeaderNames(): string[];

      Returns an array containing the unique names of the current outgoing headers. All names are lowercase.

    • Returns a shallow copy of the current outgoing headers. Since a shallow copy is used, array values may be mutated without additional calls to various header-related HTTP module methods. The keys of the returned object are the header names and the values are the respective header values. All header names are lowercase.

      The object returned by the outgoingMessage.getHeaders() method does not prototypically inherit from the JavaScript Object. This means that typical Object methods such as obj.toString(), obj.hasOwnProperty(), and others are not defined and will not work.

      outgoingMessage.setHeader('Foo', 'bar');
      outgoingMessage.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);
      
      const headers = outgoingMessage.getHeaders();
      // headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] }
      
    • getMaxListeners(): number;

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

    • name: string
      ): boolean;

      Returns true if the header identified by name is currently set in the outgoing headers. The header name is case-insensitive.

      const hasContentType = outgoingMessage.hasHeader('content-type');
      
    • eventName: string | symbol,
      listener?: Function
      ): number;

      Returns the number of listeners listening for the event named eventName. If listener is provided, it will return how many times the listener is found in the list of the listeners of the event.

      @param eventName

      The name of the event being listened for

      @param listener

      The event handler function

    • eventName: string | symbol
      ): Function[];

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

      server.on('connection', (stream) => {
        console.log('someone connected!');
      });
      console.log(util.inspect(server.listeners('connection')));
      // Prints: [ [Function] ]
      
    • off<K>(
      eventName: string | symbol,
      listener: (...args: any[]) => void
      ): this;

      Alias for emitter.removeListener().

    • event: 'close',
      listener: () => void
      ): this;

      Adds the listener function to the end of the listeners array for the event named eventName. No checks are made to see if the listener has already been added. Multiple calls passing the same combination of eventName and listener will result in the listener being added, and called, multiple times.

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

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

      By default, event listeners are invoked in the order they are added. The emitter.prependListener() method can be used as an alternative to add the event listener to the beginning of the listeners array.

      import { EventEmitter } from 'node:events';
      const myEE = new EventEmitter();
      myEE.on('foo', () => console.log('a'));
      myEE.prependListener('foo', () => console.log('b'));
      myEE.emit('foo');
      // Prints:
      //   b
      //   a
      
      @param listener

      The callback function

      event: 'drain',
      listener: () => void
      ): this;
      event: 'error',
      listener: (err: Error) => void
      ): this;
      event: 'finish',
      listener: () => void
      ): this;
      event: 'pipe',
      listener: (src: Readable) => void
      ): this;
      event: 'unpipe',
      listener: (src: Readable) => void
      ): this;
      event: string | symbol,
      listener: (...args: any[]) => void
      ): this;
    • event: 'close',
      listener: () => void
      ): this;

      Adds a one-time listener function for the event named eventName. The next time eventName is triggered, this listener is removed and then invoked.

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

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

      By default, event listeners are invoked in the order they are added. The emitter.prependOnceListener() method can be used as an alternative to add the event listener to the beginning of the listeners array.

      import { EventEmitter } from 'node:events';
      const myEE = new EventEmitter();
      myEE.once('foo', () => console.log('a'));
      myEE.prependOnceListener('foo', () => console.log('b'));
      myEE.emit('foo');
      // Prints:
      //   b
      //   a
      
      @param listener

      The callback function

      event: 'drain',
      listener: () => void
      ): this;
      event: 'error',
      listener: (err: Error) => void
      ): this;
      event: 'finish',
      listener: () => void
      ): this;
      event: 'pipe',
      listener: (src: Readable) => void
      ): this;
      event: 'unpipe',
      listener: (src: Readable) => void
      ): this;
      event: string | symbol,
      listener: (...args: any[]) => void
      ): this;
    • pipe<T extends WritableStream>(
      destination: T,
      options?: { end: boolean }
      ): T;
    • event: 'close',
      listener: () => void
      ): this;

      Adds the listener function to the beginning of the listeners array for the event named eventName. No checks are made to see if the listener has already been added. Multiple calls passing the same combination of eventName and listener will result in the listener being added, and called, multiple times.

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

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

      @param listener

      The callback function

      event: 'drain',
      listener: () => void
      ): this;
      event: 'error',
      listener: (err: Error) => void
      ): this;
      event: 'finish',
      listener: () => void
      ): this;
      event: 'pipe',
      listener: (src: Readable) => void
      ): this;
      event: 'unpipe',
      listener: (src: Readable) => void
      ): this;
      event: string | symbol,
      listener: (...args: any[]) => void
      ): this;
    • event: 'close',
      listener: () => void
      ): this;

      Adds a one-timelistener function for the event named eventName to the beginning of the listeners array. The next time eventName is triggered, this listener is removed, and then invoked.

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

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

      @param listener

      The callback function

      event: 'drain',
      listener: () => void
      ): this;
      event: 'error',
      listener: (err: Error) => void
      ): this;
      event: 'finish',
      listener: () => void
      ): this;
      event: 'pipe',
      listener: (src: Readable) => void
      ): this;
      event: 'unpipe',
      listener: (src: Readable) => void
      ): this;
      event: string | symbol,
      listener: (...args: any[]) => void
      ): this;
    • eventName: string | symbol
      ): Function[];

      Returns a copy of the array of listeners for the event named eventName, including any wrappers (such as those created by .once()).

      import { EventEmitter } from 'node:events';
      const emitter = new EventEmitter();
      emitter.once('log', () => console.log('log once'));
      
      // Returns a new Array with a function `onceWrapper` which has a property
      // `listener` which contains the original listener bound above
      const listeners = emitter.rawListeners('log');
      const logFnWrapper = listeners[0];
      
      // Logs "log once" to the console and does not unbind the `once` event
      logFnWrapper.listener();
      
      // Logs "log once" to the console and removes the listener
      logFnWrapper();
      
      emitter.on('log', () => console.log('log persistently'));
      // Will return a new Array with a single function bound by `.on()` above
      const newListeners = emitter.rawListeners('log');
      
      // Logs "log persistently" twice
      newListeners[0]();
      emitter.emit('log');
      
    • eventName?: string | symbol
      ): this;

      Removes all listeners, or those of the specified eventName.

      It is bad practice to remove listeners added elsewhere in the code, particularly when the EventEmitter instance was created by some other component or module (e.g. sockets or file streams).

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

    • name: string
      ): void;

      Removes a header that is queued for implicit sending.

      outgoingMessage.removeHeader('Content-Encoding');
      
      @param name

      Header name

    • event: 'close',
      listener: () => void
      ): this;

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

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

      removeListener() will remove, at most, one instance of a listener from the listener array. If any single listener has been added multiple times to the listener array for the specified eventName, then removeListener() must be called multiple times to remove each instance.

      Once an event is emitted, all listeners attached to it at the time of emitting are called in order. This implies that any removeListener() or removeAllListeners() calls after emitting and before the last listener finishes execution will not remove them fromemit() in progress. Subsequent events behave as expected.

      import { EventEmitter } from 'node:events';
      class MyEmitter extends EventEmitter {}
      const myEmitter = new MyEmitter();
      
      const callbackA = () => {
        console.log('A');
        myEmitter.removeListener('event', callbackB);
      };
      
      const callbackB = () => {
        console.log('B');
      };
      
      myEmitter.on('event', callbackA);
      
      myEmitter.on('event', callbackB);
      
      // callbackA removes listener callbackB but it will still be called.
      // Internal listener array at time of emit [callbackA, callbackB]
      myEmitter.emit('event');
      // Prints:
      //   A
      //   B
      
      // callbackB is now removed.
      // Internal listener array [callbackA]
      myEmitter.emit('event');
      // Prints:
      //   A
      

      Because listeners are managed using an internal array, calling this will change the position indices of any listener registered after the listener being removed. This will not impact the order in which listeners are called, but it means that any copies of the listener array as returned by the emitter.listeners() method will need to be recreated.

      When a single function has been added as a handler multiple times for a single event (as in the example below), removeListener() will remove the most recently added instance. In the example the once('ping') listener is removed:

      import { EventEmitter } from 'node:events';
      const ee = new EventEmitter();
      
      function pong() {
        console.log('pong');
      }
      
      ee.on('ping', pong);
      ee.once('ping', pong);
      ee.removeListener('ping', pong);
      
      ee.emit('ping');
      ee.emit('ping');
      

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

      event: 'drain',
      listener: () => void
      ): this;
      event: 'error',
      listener: (err: Error) => void
      ): this;
      event: 'finish',
      listener: () => void
      ): this;
      event: 'pipe',
      listener: (src: Readable) => void
      ): this;
      event: 'unpipe',
      listener: (src: Readable) => void
      ): this;
      event: string | symbol,
      listener: (...args: any[]) => void
      ): this;
    • encoding: BufferEncoding
      ): this;

      The writable.setDefaultEncoding() method sets the default encoding for a Writable stream.

      @param encoding

      The new default encoding

    • name: string,
      value: string | number | readonly string[]
      ): this;

      Sets a single header value. If the header already exists in the to-be-sent headers, its value will be replaced. Use an array of strings to send multiple headers with the same name.

      @param name

      Header name

      @param value

      Header value

    • headers: Headers | Map<string, string | number | readonly string[]>
      ): this;

      Sets multiple header values for implicit headers. headers must be an instance of Headers or Map, if a header already exists in the to-be-sent headers, its value will be replaced.

      const headers = new Headers({ foo: 'bar' });
      outgoingMessage.setHeaders(headers);
      

      or

      const headers = new Map([['foo', 'bar']]);
      outgoingMessage.setHeaders(headers);
      

      When headers have been set with outgoingMessage.setHeaders(), they will be merged with any headers passed to response.writeHead(), with the headers passed to response.writeHead() given precedence.

      // Returns content-type = text/plain
      const server = http.createServer((req, res) => {
        const headers = new Headers({ 'Content-Type': 'text/html' });
        res.setHeaders(headers);
        res.writeHead(200, { 'Content-Type': 'text/plain' });
        res.end('ok');
      });
      
    • n: number
      ): this;

      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.

    • msecs: number,
      callback?: () => void
      ): this;

      Once a socket is associated with the message and is connected, socket.setTimeout() will be called with msecs as the first parameter.

      @param callback

      Optional function to be called when a timeout occurs. Same as binding to the timeout event.

    • uncork(): void;

      The writable.uncork() method flushes all data buffered since cork was called.

      When using writable.cork() and writable.uncork() to manage the buffering of writes to a stream, defer calls to writable.uncork() using process.nextTick(). Doing so allows batching of all writable.write() calls that occur within a given Node.js event loop phase.

      stream.cork();
      stream.write('some ');
      stream.write('data ');
      process.nextTick(() => stream.uncork());
      

      If the writable.cork() method is called multiple times on a stream, the same number of calls to writable.uncork() must be called to flush the buffered data.

      stream.cork();
      stream.write('some ');
      stream.cork();
      stream.write('data ');
      process.nextTick(() => {
        stream.uncork();
        // The data will not be flushed until uncork() is called a second time.
        stream.uncork();
      });
      

      See also: writable.cork().

    • chunk: any,
      callback?: (error: undefined | null | Error) => void
      ): boolean;

      The writable.write() method writes some data to the stream, and calls the supplied callback once the data has been fully handled. If an error occurs, the callback will be called with the error as its first argument. The callback is called asynchronously and before 'error' is emitted.

      The return value is true if the internal buffer is less than the highWaterMark configured when the stream was created after admitting chunk. If false is returned, further attempts to write data to the stream should stop until the 'drain' event is emitted.

      While a stream is not draining, calls to write() will buffer chunk, and return false. Once all currently buffered chunks are drained (accepted for delivery by the operating system), the 'drain' event will be emitted. Once write() returns false, do not write more chunks until the 'drain' event is emitted. While calling write() on a stream that is not draining is allowed, Node.js will buffer all written chunks until maximum memory usage occurs, at which point it will abort unconditionally. Even before it aborts, high memory usage will cause poor garbage collector performance and high RSS (which is not typically released back to the system, even after the memory is no longer required). Since TCP sockets may never drain if the remote peer does not read the data, writing a socket that is not draining may lead to a remotely exploitable vulnerability.

      Writing data while the stream is not draining is particularly problematic for a Transform, because the Transform streams are paused by default until they are piped or a 'data' or 'readable' event handler is added.

      If the data to be written can be generated or fetched on demand, it is recommended to encapsulate the logic into a Readable and use pipe. However, if calling write() is preferred, it is possible to respect backpressure and avoid memory issues using the 'drain' event:

      function write(data, cb) {
        if (!stream.write(data)) {
          stream.once('drain', cb);
        } else {
          process.nextTick(cb);
        }
      }
      
      // Wait for cb to be called before doing any other write.
      write('hello', () => {
        console.log('Write completed, do more writes now.');
      });
      

      A Writable stream in object mode will always ignore the encoding argument.

      @param chunk

      Optional data to write. For streams not operating in object mode, chunk must be a {string}, {Buffer}, {TypedArray} or {DataView}. For object mode streams, chunk may be any JavaScript value other than null.

      @param callback

      Callback for when this chunk of data is flushed.

      @returns

      false if the stream wishes for the calling code to wait for the 'drain' event to be emitted before continuing to write additional data; otherwise true.

      chunk: any,
      encoding: BufferEncoding,
      callback?: (error: undefined | null | Error) => void
      ): boolean;

      The writable.write() method writes some data to the stream, and calls the supplied callback once the data has been fully handled. If an error occurs, the callback will be called with the error as its first argument. The callback is called asynchronously and before 'error' is emitted.

      The return value is true if the internal buffer is less than the highWaterMark configured when the stream was created after admitting chunk. If false is returned, further attempts to write data to the stream should stop until the 'drain' event is emitted.

      While a stream is not draining, calls to write() will buffer chunk, and return false. Once all currently buffered chunks are drained (accepted for delivery by the operating system), the 'drain' event will be emitted. Once write() returns false, do not write more chunks until the 'drain' event is emitted. While calling write() on a stream that is not draining is allowed, Node.js will buffer all written chunks until maximum memory usage occurs, at which point it will abort unconditionally. Even before it aborts, high memory usage will cause poor garbage collector performance and high RSS (which is not typically released back to the system, even after the memory is no longer required). Since TCP sockets may never drain if the remote peer does not read the data, writing a socket that is not draining may lead to a remotely exploitable vulnerability.

      Writing data while the stream is not draining is particularly problematic for a Transform, because the Transform streams are paused by default until they are piped or a 'data' or 'readable' event handler is added.

      If the data to be written can be generated or fetched on demand, it is recommended to encapsulate the logic into a Readable and use pipe. However, if calling write() is preferred, it is possible to respect backpressure and avoid memory issues using the 'drain' event:

      function write(data, cb) {
        if (!stream.write(data)) {
          stream.once('drain', cb);
        } else {
          process.nextTick(cb);
        }
      }
      
      // Wait for cb to be called before doing any other write.
      write('hello', () => {
        console.log('Write completed, do more writes now.');
      });
      

      A Writable stream in object mode will always ignore the encoding argument.

      @param chunk

      Optional data to write. For streams not operating in object mode, chunk must be a {string}, {Buffer}, {TypedArray} or {DataView}. For object mode streams, chunk may be any JavaScript value other than null.

      @param encoding

      The encoding, if chunk is a string.

      @param callback

      Callback for when this chunk of data is flushed.

      @returns

      false if the stream wishes for the calling code to wait for the 'drain' event to be emitted before continuing to write additional data; otherwise true.

    • signal: AbortSignal,
      resource: (event: Event) => void
      ): Disposable;

      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]();
        }
      }
      
      @returns

      Disposable that removes the abort listener.

    • static fromWeb(
      writableStream: WritableStream,
      options?: Pick<WritableOptions<Writable>, 'signal' | 'decodeStrings' | 'highWaterMark' | 'objectMode'>

      A utility method for creating a Writable from a web WritableStream.

    • emitter: EventEmitter<DefaultEventMap> | EventTarget,
      name: string | symbol
      ): Function[];

      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] ]
      }
      
    • emitter: EventEmitter<DefaultEventMap> | EventTarget
      ): number;

      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
      }
      
    • static on(
      emitter: EventEmitter,
      eventName: string | symbol,
      options?: StaticEventEmitterIteratorOptions
      ): AsyncIterator<any[]>;
      import { on, EventEmitter } from 'node:events';
      import process from 'node:process';
      
      const ee = new EventEmitter();
      
      // Emit later on
      process.nextTick(() => {
        ee.emit('foo', 'bar');
        ee.emit('foo', 42);
      });
      
      for await (const event of on(ee, 'foo')) {
        // The execution of this inner block is synchronous and it
        // processes one event at a time (even with await). Do not use
        // if concurrent execution is required.
        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:

      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 on
      process.nextTick(() => {
        ee.emit('foo', 'bar');
        ee.emit('foo', 42);
        ee.emit('close');
      });
      
      for await (const event of on(ee, 'foo', { close: ['close'] })) {
        console.log(event); // prints ['bar'] [42]
      }
      // the loop will exit after 'close' is emitted
      console.log('done'); // prints 'done'
      
      @returns

      An AsyncIterator that iterates eventName events emitted by the emitter

      static on(
      emitter: EventTarget,
      eventName: string,
      options?: StaticEventEmitterIteratorOptions
      ): AsyncIterator<any[]>;
      import { on, EventEmitter } from 'node:events';
      import process from 'node:process';
      
      const ee = new EventEmitter();
      
      // Emit later on
      process.nextTick(() => {
        ee.emit('foo', 'bar');
        ee.emit('foo', 42);
      });
      
      for await (const event of on(ee, 'foo')) {
        // The execution of this inner block is synchronous and it
        // processes one event at a time (even with await). Do not use
        // if concurrent execution is required.
        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:

      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 on
      process.nextTick(() => {
        ee.emit('foo', 'bar');
        ee.emit('foo', 42);
        ee.emit('close');
      });
      
      for await (const event of on(ee, 'foo', { close: ['close'] })) {
        console.log(event); // prints ['bar'] [42]
      }
      // the loop will exit after 'close' is emitted
      console.log('done'); // prints 'done'
      
      @returns

      An AsyncIterator that iterates eventName events emitted by the emitter

    • static once(
      emitter: EventEmitter,
      eventName: string | symbol,
      options?: StaticEventEmitterOptions
      ): Promise<any[]>;

      Creates a Promise that is fulfilled when the EventEmitter emits the given event or that is rejected if the EventEmitter emits 'error' while waiting. The Promise will resolve with an array of all the arguments emitted to the given event.

      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 boom
      

      An 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 event
      ee.emit('foo'); // Prints: Waiting for the event was canceled!
      
      static once(
      emitter: EventTarget,
      eventName: string,
      options?: StaticEventEmitterOptions
      ): Promise<any[]>;

      Creates a Promise that is fulfilled when the EventEmitter emits the given event or that is rejected if the EventEmitter emits 'error' while waiting. The Promise will resolve with an array of all the arguments emitted to the given event.

      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 boom
      

      An 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 event
      ee.emit('foo'); // Prints: Waiting for the event was canceled!
      
    • n?: number,
      ...eventTargets: EventEmitter<DefaultEventMap> | EventTarget[]
      ): void;
      import { setMaxListeners, EventEmitter } from 'node:events';
      
      const target = new EventTarget();
      const emitter = new EventEmitter();
      
      setMaxListeners(5, target, emitter);
      
      @param n

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

      @param eventTargets

      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.

    • static toWeb(
      streamWritable: Writable

      A utility method for creating a web WritableStream from a Writable.

  • class Server<Request extends typeof IncomingMessage = typeof IncomingMessage, Response extends typeof ServerResponse = typeof ServerResponse>

    • connections: number
    • headersTimeout: number

      Limit the amount of time the parser will wait to receive the complete HTTP headers.

      If the timeout expires, the server responds with status 408 without forwarding the request to the request listener and then closes the connection.

      It must be set to a non-zero value (e.g. 120 seconds) to protect against potential Denial-of-Service attacks in case the server is deployed without a reverse proxy in front.

    • keepAliveTimeout: number

      The number of milliseconds of inactivity a server needs to wait for additional incoming data, after it has finished writing the last response, before a socket will be destroyed. If the server receives new data before the keep-alive timeout has fired, it will reset the regular inactivity timeout, i.e., server.timeout.

      A value of 0 will disable the keep-alive timeout behavior on incoming connections. A value of 0 makes the http server behave similarly to Node.js versions prior to 8.0.0, which did not have a keep-alive timeout.

      The socket timeout logic is set up on connection, so changing this value only affects new connections to the server, not any existing connections.

    • readonly listening: boolean

      Indicates whether or not the server is listening for connections.

    • maxConnections: number

      Set this property to reject connections when the server's connection count gets high.

      It is not recommended to use this option once a socket has been sent to a child with child_process.fork().

    • maxHeadersCount: null | number

      Limits maximum incoming headers count. If set to 0, no limit will be applied.

    • maxRequestsPerSocket: null | number

      The maximum number of requests socket can handle before closing keep alive connection.

      A value of 0 will disable the limit.

      When the limit is reached it will set the Connection header value to close, but will not actually close the connection, subsequent requests sent after the limit is reached will get 503 Service Unavailable as a response.

    • requestTimeout: number

      Sets the timeout value in milliseconds for receiving the entire request from the client.

      If the timeout expires, the server responds with status 408 without forwarding the request to the request listener and then closes the connection.

      It must be set to a non-zero value (e.g. 120 seconds) to protect against potential Denial-of-Service attacks in case the server is deployed without a reverse proxy in front.

    • timeout: number

      The number of milliseconds of inactivity before a socket is presumed to have timed out.

      A value of 0 will disable the timeout behavior on incoming connections.

      The socket timeout logic is set up on connection, so changing this value only affects new connections to the server, not any existing connections.

    • static captureRejections: boolean

      Value: boolean

      Change the default captureRejections option on all new EventEmitter objects.

    • readonly static captureRejectionSymbol: typeof captureRejectionSymbol

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

      See how to write a custom rejection handler.

    • static defaultMaxListeners: number

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

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

    • [Symbol.asyncDispose](): Promise<void>;

      Calls () and returns a promise that fulfills when the server has closed.

    • error: Error,
      event: string | symbol,
      ...args: AnyRest
      ): void;
    • event: string,
      listener: (...args: any[]) => void
      ): this;

      events.EventEmitter

      1. close
      2. connection
      3. error
      4. listening
      5. drop
      event: 'close',
      listener: () => void
      ): this;

      events.EventEmitter

      1. close
      2. connection
      3. error
      4. listening
      5. drop
      event: 'connection',
      listener: (socket: Socket) => void
      ): this;

      events.EventEmitter

      1. close
      2. connection
      3. error
      4. listening
      5. drop
      event: 'error',
      listener: (err: Error) => void
      ): this;

      events.EventEmitter

      1. close
      2. connection
      3. error
      4. listening
      5. drop
      event: 'listening',
      listener: () => void
      ): this;

      events.EventEmitter

      1. close
      2. connection
      3. error
      4. listening
      5. drop
      event: 'checkContinue',
      listener: RequestListener<Request, Response>
      ): this;

      events.EventEmitter

      1. close
      2. connection
      3. error
      4. listening
      5. drop
      event: 'checkExpectation',
      listener: RequestListener<Request, Response>
      ): this;
      event: 'clientError',
      listener: (err: Error, socket: Duplex) => void
      ): this;
      event: 'connect',
      listener: (req: InstanceType<Request>, socket: Duplex, head: Buffer) => void
      ): this;
      event: 'dropRequest',
      listener: (req: InstanceType<Request>, socket: Duplex) => void
      ): this;
      event: 'request',
      listener: RequestListener<Request, Response>
      ): this;
      event: 'upgrade',
      listener: (req: InstanceType<Request>, socket: Duplex, head: Buffer) => void
      ): this;
    • address(): null | string | AddressInfo;

      Returns the bound address, the address family name, and port of the server as reported by the operating system if listening on an IP socket (useful to find which port was assigned when getting an OS-assigned address):{ port: 12346, family: 'IPv4', address: '127.0.0.1' }.

      For a server listening on a pipe or Unix domain socket, the name is returned as a string.

      const server = net.createServer((socket) => {
        socket.end('goodbye\n');
      }).on('error', (err) => {
        // Handle errors here.
        throw err;
      });
      
      // Grab an arbitrary unused port.
      server.listen(() => {
        console.log('opened server on', server.address());
      });
      

      server.address() returns null before the 'listening' event has been emitted or after calling server.close().

    • callback?: (err?: Error) => void
      ): this;

      Stops the server from accepting new connections and keeps existing connections. This function is asynchronous, the server is finally closed when all connections are ended and the server emits a 'close' event. The optional callback will be called once the 'close' event occurs. Unlike that event, it will be called with an Error as its only argument if the server was not open when it was closed.

      @param callback

      Called when the server is closed.

    • Closes all connections connected to this server.

    • Closes all connections connected to this server which are not sending a request or waiting for a response.

    • event: string,
      ...args: any[]
      ): boolean;

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

      Returns true if the event had listeners, false otherwise.

      import { EventEmitter } from 'node:events';
      const myEmitter = new EventEmitter();
      
      // First listener
      myEmitter.on('event', function firstListener() {
        console.log('Helloooo! first listener');
      });
      // Second listener
      myEmitter.on('event', function secondListener(arg1, arg2) {
        console.log(`event with parameters ${arg1}, ${arg2} in second listener`);
      });
      // Third listener
      myEmitter.on('event', function thirdListener(...args) {
        const parameters = args.join(', ');
        console.log(`event with parameters ${parameters} in third listener`);
      });
      
      console.log(myEmitter.listeners('event'));
      
      myEmitter.emit('event', 1, 2, 3, 4, 5);
      
      // Prints:
      // [
      //   [Function: firstListener],
      //   [Function: secondListener],
      //   [Function: thirdListener]
      // ]
      // Helloooo! first listener
      // event with parameters 1, 2 in second listener
      // event with parameters 1, 2, 3, 4, 5 in third listener
      
      event: 'close'
      ): boolean;
      event: 'connection',
      socket: Socket
      ): boolean;
      event: 'error',
      err: Error
      ): boolean;
      event: 'listening'
      ): boolean;
      event: 'checkContinue',
      req: InstanceType<Request>,
      res: InstanceType<Response> & { req: InstanceType<Request> }
      ): boolean;
      event: 'checkExpectation',
      req: InstanceType<Request>,
      res: InstanceType<Response> & { req: InstanceType<Request> }
      ): boolean;
      event: 'clientError',
      err: Error,
      socket: Duplex
      ): boolean;
      event: 'connect',
      req: InstanceType<Request>,
      socket: Duplex,
      head: Buffer
      ): boolean;
      event: 'dropRequest',
      req: InstanceType<Request>,
      socket: Duplex
      ): boolean;
      event: 'request',
      req: InstanceType<Request>,
      res: InstanceType<Response> & { req: InstanceType<Request> }
      ): boolean;
      event: 'upgrade',
      req: InstanceType<Request>,
      socket: Duplex,
      head: Buffer
      ): boolean;
    • eventNames(): string | symbol[];

      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) ]
      
    • cb: (error: null | Error, count: number) => void
      ): void;

      Asynchronously get the number of concurrent connections on the server. Works when sockets were sent to forks.

      Callback should take two arguments err and count.

    • getMaxListeners(): number;

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

    • port?: number,
      hostname?: string,
      backlog?: number,
      listeningListener?: () => void
      ): this;

      Start a server listening for connections. A net.Server can be a TCP or an IPC server depending on what it listens to.

      Possible signatures:

      • server.listen(handle[, backlog][, callback])
      • server.listen(options[, callback])
      • server.listen(path[, backlog][, callback]) for IPC servers
      • server.listen([port[, host[, backlog]]][, callback]) for TCP servers

      This function is asynchronous. When the server starts listening, the 'listening' event will be emitted. The last parameter callbackwill be added as a listener for the 'listening' event.

      All listen() methods can take a backlog parameter to specify the maximum length of the queue of pending connections. The actual length will be determined by the OS through sysctl settings such as tcp_max_syn_backlog and somaxconn on Linux. The default value of this parameter is 511 (not 512).

      All Socket are set to SO_REUSEADDR (see socket(7) for details).

      The server.listen() method can be called again if and only if there was an error during the first server.listen() call or server.close() has been called. Otherwise, an ERR_SERVER_ALREADY_LISTEN error will be thrown.

      One of the most common errors raised when listening is EADDRINUSE. This happens when another server is already listening on the requestedport/path/handle. One way to handle this would be to retry after a certain amount of time:

      server.on('error', (e) => {
        if (e.code === 'EADDRINUSE') {
          console.error('Address in use, retrying...');
          setTimeout(() => {
            server.close();
            server.listen(PORT, HOST);
          }, 1000);
        }
      });
      
      port?: number,
      hostname?: string,
      listeningListener?: () => void
      ): this;

      Start a server listening for connections. A net.Server can be a TCP or an IPC server depending on what it listens to.

      Possible signatures:

      • server.listen(handle[, backlog][, callback])
      • server.listen(options[, callback])
      • server.listen(path[, backlog][, callback]) for IPC servers
      • server.listen([port[, host[, backlog]]][, callback]) for TCP servers

      This function is asynchronous. When the server starts listening, the 'listening' event will be emitted. The last parameter callbackwill be added as a listener for the 'listening' event.

      All listen() methods can take a backlog parameter to specify the maximum length of the queue of pending connections. The actual length will be determined by the OS through sysctl settings such as tcp_max_syn_backlog and somaxconn on Linux. The default value of this parameter is 511 (not 512).

      All Socket are set to SO_REUSEADDR (see socket(7) for details).

      The server.listen() method can be called again if and only if there was an error during the first server.listen() call or server.close() has been called. Otherwise, an ERR_SERVER_ALREADY_LISTEN error will be thrown.

      One of the most common errors raised when listening is EADDRINUSE. This happens when another server is already listening on the requestedport/path/handle. One way to handle this would be to retry after a certain amount of time:

      server.on('error', (e) => {
        if (e.code === 'EADDRINUSE') {
          console.error('Address in use, retrying...');
          setTimeout(() => {
            server.close();
            server.listen(PORT, HOST);
          }, 1000);
        }
      });
      
      port?: number,
      backlog?: number,
      listeningListener?: () => void
      ): this;

      Start a server listening for connections. A net.Server can be a TCP or an IPC server depending on what it listens to.

      Possible signatures:

      • server.listen(handle[, backlog][, callback])
      • server.listen(options[, callback])
      • server.listen(path[, backlog][, callback]) for IPC servers
      • server.listen([port[, host[, backlog]]][, callback]) for TCP servers

      This function is asynchronous. When the server starts listening, the 'listening' event will be emitted. The last parameter callbackwill be added as a listener for the 'listening' event.

      All listen() methods can take a backlog parameter to specify the maximum length of the queue of pending connections. The actual length will be determined by the OS through sysctl settings such as tcp_max_syn_backlog and somaxconn on Linux. The default value of this parameter is 511 (not 512).

      All Socket are set to SO_REUSEADDR (see socket(7) for details).

      The server.listen() method can be called again if and only if there was an error during the first server.listen() call or server.close() has been called. Otherwise, an ERR_SERVER_ALREADY_LISTEN error will be thrown.

      One of the most common errors raised when listening is EADDRINUSE. This happens when another server is already listening on the requestedport/path/handle. One way to handle this would be to retry after a certain amount of time:

      server.on('error', (e) => {
        if (e.code === 'EADDRINUSE') {
          console.error('Address in use, retrying...');
          setTimeout(() => {
            server.close();
            server.listen(PORT, HOST);
          }, 1000);
        }
      });
      
      port?: number,
      listeningListener?: () => void
      ): this;

      Start a server listening for connections. A net.Server can be a TCP or an IPC server depending on what it listens to.

      Possible signatures:

      • server.listen(handle[, backlog][, callback])
      • server.listen(options[, callback])
      • server.listen(path[, backlog][, callback]) for IPC servers
      • server.listen([port[, host[, backlog]]][, callback]) for TCP servers

      This function is asynchronous. When the server starts listening, the 'listening' event will be emitted. The last parameter callbackwill be added as a listener for the 'listening' event.

      All listen() methods can take a backlog parameter to specify the maximum length of the queue of pending connections. The actual length will be determined by the OS through sysctl settings such as tcp_max_syn_backlog and somaxconn on Linux. The default value of this parameter is 511 (not 512).

      All Socket are set to SO_REUSEADDR (see socket(7) for details).

      The server.listen() method can be called again if and only if there was an error during the first server.listen() call or server.close() has been called. Otherwise, an ERR_SERVER_ALREADY_LISTEN error will be thrown.

      One of the most common errors raised when listening is EADDRINUSE. This happens when another server is already listening on the requestedport/path/handle. One way to handle this would be to retry after a certain amount of time:

      server.on('error', (e) => {
        if (e.code === 'EADDRINUSE') {
          console.error('Address in use, retrying...');
          setTimeout(() => {
            server.close();
            server.listen(PORT, HOST);
          }, 1000);
        }
      });
      
      path: string,
      backlog?: number,
      listeningListener?: () => void
      ): this;

      Start a server listening for connections. A net.Server can be a TCP or an IPC server depending on what it listens to.

      Possible signatures:

      • server.listen(handle[, backlog][, callback])
      • server.listen(options[, callback])
      • server.listen(path[, backlog][, callback]) for IPC servers
      • server.listen([port[, host[, backlog]]][, callback]) for TCP servers

      This function is asynchronous. When the server starts listening, the 'listening' event will be emitted. The last parameter callbackwill be added as a listener for the 'listening' event.

      All listen() methods can take a backlog parameter to specify the maximum length of the queue of pending connections. The actual length will be determined by the OS through sysctl settings such as tcp_max_syn_backlog and somaxconn on Linux. The default value of this parameter is 511 (not 512).

      All Socket are set to SO_REUSEADDR (see socket(7) for details).

      The server.listen() method can be called again if and only if there was an error during the first server.listen() call or server.close() has been called. Otherwise, an ERR_SERVER_ALREADY_LISTEN error will be thrown.

      One of the most common errors raised when listening is EADDRINUSE. This happens when another server is already listening on the requestedport/path/handle. One way to handle this would be to retry after a certain amount of time:

      server.on('error', (e) => {
        if (e.code === 'EADDRINUSE') {
          console.error('Address in use, retrying...');
          setTimeout(() => {
            server.close();
            server.listen(PORT, HOST);
          }, 1000);
        }
      });
      
      path: string,
      listeningListener?: () => void
      ): this;

      Start a server listening for connections. A net.Server can be a TCP or an IPC server depending on what it listens to.

      Possible signatures:

      • server.listen(handle[, backlog][, callback])
      • server.listen(options[, callback])
      • server.listen(path[, backlog][, callback]) for IPC servers
      • server.listen([port[, host[, backlog]]][, callback]) for TCP servers

      This function is asynchronous. When the server starts listening, the 'listening' event will be emitted. The last parameter callbackwill be added as a listener for the 'listening' event.

      All listen() methods can take a backlog parameter to specify the maximum length of the queue of pending connections. The actual length will be determined by the OS through sysctl settings such as tcp_max_syn_backlog and somaxconn on Linux. The default value of this parameter is 511 (not 512).

      All Socket are set to SO_REUSEADDR (see socket(7) for details).

      The server.listen() method can be called again if and only if there was an error during the first server.listen() call or server.close() has been called. Otherwise, an ERR_SERVER_ALREADY_LISTEN error will be thrown.

      One of the most common errors raised when listening is EADDRINUSE. This happens when another server is already listening on the requestedport/path/handle. One way to handle this would be to retry after a certain amount of time:

      server.on('error', (e) => {
        if (e.code === 'EADDRINUSE') {
          console.error('Address in use, retrying...');
          setTimeout(() => {
            server.close();
            server.listen(PORT, HOST);
          }, 1000);
        }
      });
      
      options: ListenOptions,
      listeningListener?: () => void
      ): this;

      Start a server listening for connections. A net.Server can be a TCP or an IPC server depending on what it listens to.

      Possible signatures:

      • server.listen(handle[, backlog][, callback])
      • server.listen(options[, callback])
      • server.listen(path[, backlog][, callback]) for IPC servers
      • server.listen([port[, host[, backlog]]][, callback]) for TCP servers

      This function is asynchronous. When the server starts listening, the 'listening' event will be emitted. The last parameter callbackwill be added as a listener for the 'listening' event.

      All listen() methods can take a backlog parameter to specify the maximum length of the queue of pending connections. The actual length will be determined by the OS through sysctl settings such as tcp_max_syn_backlog and somaxconn on Linux. The default value of this parameter is 511 (not 512).

      All Socket are set to SO_REUSEADDR (see socket(7) for details).

      The server.listen() method can be called again if and only if there was an error during the first server.listen() call or server.close() has been called. Otherwise, an ERR_SERVER_ALREADY_LISTEN error will be thrown.

      One of the most common errors raised when listening is EADDRINUSE. This happens when another server is already listening on the requestedport/path/handle. One way to handle this would be to retry after a certain amount of time:

      server.on('error', (e) => {
        if (e.code === 'EADDRINUSE') {
          console.error('Address in use, retrying...');
          setTimeout(() => {
            server.close();
            server.listen(PORT, HOST);
          }, 1000);
        }
      });
      
      handle: any,
      backlog?: number,
      listeningListener?: () => void
      ): this;

      Start a server listening for connections. A net.Server can be a TCP or an IPC server depending on what it listens to.

      Possible signatures:

      • server.listen(handle[, backlog][, callback])
      • server.listen(options[, callback])
      • server.listen(path[, backlog][, callback]) for IPC servers
      • server.listen([port[, host[, backlog]]][, callback]) for TCP servers

      This function is asynchronous. When the server starts listening, the 'listening' event will be emitted. The last parameter callbackwill be added as a listener for the 'listening' event.

      All listen() methods can take a backlog parameter to specify the maximum length of the queue of pending connections. The actual length will be determined by the OS through sysctl settings such as tcp_max_syn_backlog and somaxconn on Linux. The default value of this parameter is 511 (not 512).

      All Socket are set to SO_REUSEADDR (see socket(7) for details).

      The server.listen() method can be called again if and only if there was an error during the first server.listen() call or server.close() has been called. Otherwise, an ERR_SERVER_ALREADY_LISTEN error will be thrown.

      One of the most common errors raised when listening is EADDRINUSE. This happens when another server is already listening on the requestedport/path/handle. One way to handle this would be to retry after a certain amount of time:

      server.on('error', (e) => {
        if (e.code === 'EADDRINUSE') {
          console.error('Address in use, retrying...');
          setTimeout(() => {
            server.close();
            server.listen(PORT, HOST);
          }, 1000);
        }
      });
      
      handle: any,
      listeningListener?: () => void
      ): this;

      Start a server listening for connections. A net.Server can be a TCP or an IPC server depending on what it listens to.

      Possible signatures:

      • server.listen(handle[, backlog][, callback])
      • server.listen(options[, callback])
      • server.listen(path[, backlog][, callback]) for IPC servers
      • server.listen([port[, host[, backlog]]][, callback]) for TCP servers

      This function is asynchronous. When the server starts listening, the 'listening' event will be emitted. The last parameter callbackwill be added as a listener for the 'listening' event.

      All listen() methods can take a backlog parameter to specify the maximum length of the queue of pending connections. The actual length will be determined by the OS through sysctl settings such as tcp_max_syn_backlog and somaxconn on Linux. The default value of this parameter is 511 (not 512).

      All Socket are set to SO_REUSEADDR (see socket(7) for details).

      The server.listen() method can be called again if and only if there was an error during the first server.listen() call or server.close() has been called. Otherwise, an ERR_SERVER_ALREADY_LISTEN error will be thrown.

      One of the most common errors raised when listening is EADDRINUSE. This happens when another server is already listening on the requestedport/path/handle. One way to handle this would be to retry after a certain amount of time:

      server.on('error', (e) => {
        if (e.code === 'EADDRINUSE') {
          console.error('Address in use, retrying...');
          setTimeout(() => {
            server.close();
            server.listen(PORT, HOST);
          }, 1000);
        }
      });
      
    • eventName: string | symbol,
      listener?: Function
      ): number;

      Returns the number of listeners listening for the event named eventName. If listener is provided, it will return how many times the listener is found in the list of the listeners of the event.

      @param eventName

      The name of the event being listened for

      @param listener

      The event handler function

    • eventName: string | symbol
      ): Function[];

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

      server.on('connection', (stream) => {
        console.log('someone connected!');
      });
      console.log(util.inspect(server.listeners('connection')));
      // Prints: [ [Function] ]
      
    • off<K>(
      eventName: string | symbol,
      listener: (...args: any[]) => void
      ): this;

      Alias for emitter.removeListener().

    • event: string,
      listener: (...args: any[]) => void
      ): this;

      Adds the listener function to the end of the listeners array for the event named eventName. No checks are made to see if the listener has already been added. Multiple calls passing the same combination of eventName and listener will result in the listener being added, and called, multiple times.

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

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

      By default, event listeners are invoked in the order they are added. The emitter.prependListener() method can be used as an alternative to add the event listener to the beginning of the listeners array.

      import { EventEmitter } from 'node:events';
      const myEE = new EventEmitter();
      myEE.on('foo', () => console.log('a'));
      myEE.prependListener('foo', () => console.log('b'));
      myEE.emit('foo');
      // Prints:
      //   b
      //   a
      
      @param listener

      The callback function

      event: 'close',
      listener: () => void
      ): this;
      event: 'connection',
      listener: (socket: Socket) => void
      ): this;
      event: 'error',
      listener: (err: Error) => void
      ): this;
      event: 'listening',
      listener: () => void
      ): this;
      event: 'checkContinue',
      listener: RequestListener<Request, Response>
      ): this;
      event: 'checkExpectation',
      listener: RequestListener<Request, Response>
      ): this;
      event: 'clientError',
      listener: (err: Error, socket: Duplex) => void
      ): this;
      event: 'connect',
      listener: (req: InstanceType<Request>, socket: Duplex, head: Buffer) => void
      ): this;
      event: 'dropRequest',
      listener: (req: InstanceType<Request>, socket: Duplex) => void
      ): this;
      event: 'request',
      listener: RequestListener<Request, Response>
      ): this;
      event: 'upgrade',
      listener: (req: InstanceType<Request>, socket: Duplex, head: Buffer) => void
      ): this;
    • event: string,
      listener: (...args: any[]) => void
      ): this;

      Adds a one-time listener function for the event named eventName. The next time eventName is triggered, this listener is removed and then invoked.

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

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

      By default, event listeners are invoked in the order they are added. The emitter.prependOnceListener() method can be used as an alternative to add the event listener to the beginning of the listeners array.

      import { EventEmitter } from 'node:events';
      const myEE = new EventEmitter();
      myEE.once('foo', () => console.log('a'));
      myEE.prependOnceListener('foo', () => console.log('b'));
      myEE.emit('foo');
      // Prints:
      //   b
      //   a
      
      @param listener

      The callback function

      event: 'close',
      listener: () => void
      ): this;
      event: 'connection',
      listener: (socket: Socket) => void
      ): this;
      event: 'error',
      listener: (err: Error) => void
      ): this;
      event: 'listening',
      listener: () => void
      ): this;
      event: 'checkContinue',
      listener: RequestListener<Request, Response>
      ): this;
      event: 'checkExpectation',
      listener: RequestListener<Request, Response>
      ): this;
      event: 'clientError',
      listener: (err: Error, socket: Duplex) => void
      ): this;
      event: 'connect',
      listener: (req: InstanceType<Request>, socket: Duplex, head: Buffer) => void
      ): this;
      event: 'dropRequest',
      listener: (req: InstanceType<Request>, socket: Duplex) => void
      ): this;
      event: 'request',
      listener: RequestListener<Request, Response>
      ): this;
      event: 'upgrade',
      listener: (req: InstanceType<Request>, socket: Duplex, head: Buffer) => void
      ): this;
    • event: string,
      listener: (...args: any[]) => void
      ): this;

      Adds the listener function to the beginning of the listeners array for the event named eventName. No checks are made to see if the listener has already been added. Multiple calls passing the same combination of eventName and listener will result in the listener being added, and called, multiple times.

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

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

      @param listener

      The callback function

      event: 'close',
      listener: () => void
      ): this;
      event: 'connection',
      listener: (socket: Socket) => void
      ): this;
      event: 'error',
      listener: (err: Error) => void
      ): this;
      event: 'listening',
      listener: () => void
      ): this;
      event: 'checkContinue',
      listener: RequestListener<Request, Response>
      ): this;
      event: 'checkExpectation',
      listener: RequestListener<Request, Response>
      ): this;
      event: 'clientError',
      listener: (err: Error, socket: Duplex) => void
      ): this;
      event: 'connect',
      listener: (req: InstanceType<Request>, socket: Duplex, head: Buffer) => void
      ): this;
      event: 'dropRequest',
      listener: (req: InstanceType<Request>, socket: Duplex) => void
      ): this;
      event: 'request',
      listener: RequestListener<Request, Response>
      ): this;
      event: 'upgrade',
      listener: (req: InstanceType<Request>, socket: Duplex, head: Buffer) => void
      ): this;
    • event: string,
      listener: (...args: any[]) => void
      ): this;

      Adds a one-timelistener function for the event named eventName to the beginning of the listeners array. The next time eventName is triggered, this listener is removed, and then invoked.

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

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

      @param listener

      The callback function

      event: 'close',
      listener: () => void
      ): this;
      event: 'connection',
      listener: (socket: Socket) => void
      ): this;
      event: 'error',
      listener: (err: Error) => void
      ): this;
      event: 'listening',
      listener: () => void
      ): this;
      event: 'checkContinue',
      listener: RequestListener<Request, Response>
      ): this;
      event: 'checkExpectation',
      listener: RequestListener<Request, Response>
      ): this;
      event: 'clientError',
      listener: (err: Error, socket: Duplex) => void
      ): this;
      event: 'connect',
      listener: (req: InstanceType<Request>, socket: Duplex, head: Buffer) => void
      ): this;
      event: 'dropRequest',
      listener: (req: InstanceType<Request>, socket: Duplex) => void
      ): this;
      event: 'request',
      listener: RequestListener<Request, Response>
      ): this;
      event: 'upgrade',
      listener: (req: InstanceType<Request>, socket: Duplex, head: Buffer) => void
      ): this;
    • eventName: string | symbol
      ): Function[];

      Returns a copy of the array of listeners for the event named eventName, including any wrappers (such as those created by .once()).

      import { EventEmitter } from 'node:events';
      const emitter = new EventEmitter();
      emitter.once('log', () => console.log('log once'));
      
      // Returns a new Array with a function `onceWrapper` which has a property
      // `listener` which contains the original listener bound above
      const listeners = emitter.rawListeners('log');
      const logFnWrapper = listeners[0];
      
      // Logs "log once" to the console and does not unbind the `once` event
      logFnWrapper.listener();
      
      // Logs "log once" to the console and removes the listener
      logFnWrapper();
      
      emitter.on('log', () => console.log('log persistently'));
      // Will return a new Array with a single function bound by `.on()` above
      const newListeners = emitter.rawListeners('log');
      
      // Logs "log persistently" twice
      newListeners[0]();
      emitter.emit('log');
      
    • ref(): this;

      Opposite of unref(), calling ref() on a previously unrefed server will not let the program exit if it's the only server left (the default behavior). If the server is refed calling ref() again will have no effect.

    • eventName?: string | symbol
      ): this;

      Removes all listeners, or those of the specified eventName.

      It is bad practice to remove listeners added elsewhere in the code, particularly when the EventEmitter instance was created by some other component or module (e.g. sockets or file streams).

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

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

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

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

      removeListener() will remove, at most, one instance of a listener from the listener array. If any single listener has been added multiple times to the listener array for the specified eventName, then removeListener() must be called multiple times to remove each instance.

      Once an event is emitted, all listeners attached to it at the time of emitting are called in order. This implies that any removeListener() or removeAllListeners() calls after emitting and before the last listener finishes execution will not remove them fromemit() in progress. Subsequent events behave as expected.

      import { EventEmitter } from 'node:events';
      class MyEmitter extends EventEmitter {}
      const myEmitter = new MyEmitter();
      
      const callbackA = () => {
        console.log('A');
        myEmitter.removeListener('event', callbackB);
      };
      
      const callbackB = () => {
        console.log('B');
      };
      
      myEmitter.on('event', callbackA);
      
      myEmitter.on('event', callbackB);
      
      // callbackA removes listener callbackB but it will still be called.
      // Internal listener array at time of emit [callbackA, callbackB]
      myEmitter.emit('event');
      // Prints:
      //   A
      //   B
      
      // callbackB is now removed.
      // Internal listener array [callbackA]
      myEmitter.emit('event');
      // Prints:
      //   A
      

      Because listeners are managed using an internal array, calling this will change the position indices of any listener registered after the listener being removed. This will not impact the order in which listeners are called, but it means that any copies of the listener array as returned by the emitter.listeners() method will need to be recreated.

      When a single function has been added as a handler multiple times for a single event (as in the example below), removeListener() will remove the most recently added instance. In the example the once('ping') listener is removed:

      import { EventEmitter } from 'node:events';
      const ee = new EventEmitter();
      
      function pong() {
        console.log('pong');
      }
      
      ee.on('ping', pong);
      ee.once('ping', pong);
      ee.removeListener('ping', pong);
      
      ee.emit('ping');
      ee.emit('ping');
      

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

    • n: number
      ): this;

      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.

    • msecs?: number,
      callback?: (socket: Socket) => void
      ): this;

      Sets the timeout value for sockets, and emits a 'timeout' event on the Server object, passing the socket as an argument, if a timeout occurs.

      If there is a 'timeout' event listener on the Server object, then it will be called with the timed-out socket as an argument.

      By default, the Server does not timeout sockets. However, if a callback is assigned to the Server's 'timeout' event, timeouts must be handled explicitly.

      callback: (socket: Socket) => void
      ): this;

      Sets the timeout value for sockets, and emits a 'timeout' event on the Server object, passing the socket as an argument, if a timeout occurs.

      If there is a 'timeout' event listener on the Server object, then it will be called with the timed-out socket as an argument.

      By default, the Server does not timeout sockets. However, if a callback is assigned to the Server's 'timeout' event, timeouts must be handled explicitly.

    • unref(): this;

      Calling unref() on a server will allow the program to exit if this is the only active server in the event system. If the server is already unrefed callingunref() again will have no effect.

    • signal: AbortSignal,
      resource: (event: Event) => void
      ): Disposable;

      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]();
        }
      }
      
      @returns

      Disposable that removes the abort listener.

    • emitter: EventEmitter<DefaultEventMap> | EventTarget,
      name: string | symbol
      ): Function[];

      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] ]
      }
      
    • emitter: EventEmitter<DefaultEventMap> | EventTarget
      ): number;

      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
      }
      
    • static on(
      emitter: EventEmitter,
      eventName: string | symbol,
      options?: StaticEventEmitterIteratorOptions
      ): AsyncIterator<any[]>;
      import { on, EventEmitter } from 'node:events';
      import process from 'node:process';
      
      const ee = new EventEmitter();
      
      // Emit later on
      process.nextTick(() => {
        ee.emit('foo', 'bar');
        ee.emit('foo', 42);
      });
      
      for await (const event of on(ee, 'foo')) {
        // The execution of this inner block is synchronous and it
        // processes one event at a time (even with await). Do not use
        // if concurrent execution is required.
        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:

      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 on
      process.nextTick(() => {
        ee.emit('foo', 'bar');
        ee.emit('foo', 42);
        ee.emit('close');
      });
      
      for await (const event of on(ee, 'foo', { close: ['close'] })) {
        console.log(event); // prints ['bar'] [42]
      }
      // the loop will exit after 'close' is emitted
      console.log('done'); // prints 'done'
      
      @returns

      An AsyncIterator that iterates eventName events emitted by the emitter

      static on(
      emitter: EventTarget,
      eventName: string,
      options?: StaticEventEmitterIteratorOptions
      ): AsyncIterator<any[]>;
      import { on, EventEmitter } from 'node:events';
      import process from 'node:process';
      
      const ee = new EventEmitter();
      
      // Emit later on
      process.nextTick(() => {
        ee.emit('foo', 'bar');
        ee.emit('foo', 42);
      });
      
      for await (const event of on(ee, 'foo')) {
        // The execution of this inner block is synchronous and it
        // processes one event at a time (even with await). Do not use
        // if concurrent execution is required.
        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:

      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 on
      process.nextTick(() => {
        ee.emit('foo', 'bar');
        ee.emit('foo', 42);
        ee.emit('close');
      });
      
      for await (const event of on(ee, 'foo', { close: ['close'] })) {
        console.log(event); // prints ['bar'] [42]
      }
      // the loop will exit after 'close' is emitted
      console.log('done'); // prints 'done'
      
      @returns

      An AsyncIterator that iterates eventName events emitted by the emitter

    • static once(
      emitter: EventEmitter,
      eventName: string | symbol,
      options?: StaticEventEmitterOptions
      ): Promise<any[]>;

      Creates a Promise that is fulfilled when the EventEmitter emits the given event or that is rejected if the EventEmitter emits 'error' while waiting. The Promise will resolve with an array of all the arguments emitted to the given event.

      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 boom
      

      An 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 event
      ee.emit('foo'); // Prints: Waiting for the event was canceled!
      
      static once(
      emitter: EventTarget,
      eventName: string,
      options?: StaticEventEmitterOptions
      ): Promise<any[]>;

      Creates a Promise that is fulfilled when the EventEmitter emits the given event or that is rejected if the EventEmitter emits 'error' while waiting. The Promise will resolve with an array of all the arguments emitted to the given event.

      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 boom
      

      An 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 event
      ee.emit('foo'); // Prints: Waiting for the event was canceled!
      
    • n?: number,
      ...eventTargets: EventEmitter<DefaultEventMap> | EventTarget[]
      ): void;
      import { setMaxListeners, EventEmitter } from 'node:events';
      
      const target = new EventTarget();
      const emitter = new EventEmitter();
      
      setMaxListeners(5, target, emitter);
      
      @param n

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

      @param eventTargets

      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.

  • class ServerResponse<Request extends IncomingMessage = IncomingMessage>

    This object is created internally by an HTTP server, not by the user. It is passed as the second parameter to the 'request' event.

    • readonly closed: boolean

      Is true after 'close' has been emitted.

    • destroyed: boolean

      Is true after writable.destroy() has been called.

    • readonly errored: null | Error

      Returns error if the stream has been destroyed with an error.

    • readonly headersSent: boolean

      Read-only. true if the headers were sent, otherwise false.

    • readonly req: Request
    • sendDate: boolean
    • readonly socket: null | Socket

      Reference to the underlying socket. Usually, users will not want to access this property.

      After calling outgoingMessage.end(), this property will be nulled.

    • statusCode: number

      When using implicit headers (not calling response.writeHead() explicitly), this property controls the status code that will be sent to the client when the headers get flushed.

      response.statusCode = 404;
      

      After response header was sent to the client, this property indicates the status code which was sent out.

    • statusMessage: string

      When using implicit headers (not calling response.writeHead() explicitly), this property controls the status message that will be sent to the client when the headers get flushed. If this is left as undefined then the standard message for the status code will be used.

      response.statusMessage = 'Not found';
      

      After response header was sent to the client, this property indicates the status message which was sent out.

    • strictContentLength: boolean

      If set to true, Node.js will check whether the Content-Length header value and the size of the body, in bytes, are equal. Mismatching the Content-Length header value will result in an Error being thrown, identified by code:``'ERR_HTTP_CONTENT_LENGTH_MISMATCH'.

    • readonly writable: boolean

      Is true if it is safe to call writable.write(), which means the stream has not been destroyed, errored, or ended.

    • readonly writableCorked: number

      Number of times writable.uncork() needs to be called in order to fully uncork the stream.

    • readonly writableEnded: boolean

      Is true after writable.end() has been called. This property does not indicate whether the data has been flushed, for this use writable.writableFinished instead.

    • readonly writableFinished: boolean

      Is set to true immediately before the 'finish' event is emitted.

    • readonly writableHighWaterMark: number

      Return the value of highWaterMark passed when creating this Writable.

    • readonly writableLength: number

      This property contains the number of bytes (or objects) in the queue ready to be written. The value provides introspection data regarding the status of the highWaterMark.

    • readonly writableNeedDrain: boolean

      Is true if the stream's buffer has been full and stream will emit 'drain'.

    • readonly writableObjectMode: boolean

      Getter for the property objectMode of a given Writable stream.

    • static captureRejections: boolean

      Value: boolean

      Change the default captureRejections option on all new EventEmitter objects.

    • readonly static captureRejectionSymbol: typeof captureRejectionSymbol

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

      See how to write a custom rejection handler.

    • static defaultMaxListeners: number

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

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

    • callback: (error?: null | Error) => void
      ): void;
    • error: null | Error,
      callback: (error?: null | Error) => void
      ): void;
    • callback: (error?: null | Error) => void
      ): void;
    • chunk: any,
      encoding: BufferEncoding,
      callback: (error?: null | Error) => void
      ): void;
    • chunks: { chunk: any; encoding: BufferEncoding }[],
      callback: (error?: null | Error) => void
      ): void;
    • error: Error,
      event: string | symbol,
      ...args: AnyRest
      ): void;
    • event: 'close',
      listener: () => void
      ): this;

      Event emitter The defined events on documents including:

      1. close
      2. drain
      3. error
      4. finish
      5. pipe
      6. unpipe
      event: 'drain',
      listener: () => void
      ): this;

      Event emitter The defined events on documents including:

      1. close
      2. drain
      3. error
      4. finish
      5. pipe
      6. unpipe
      event: 'error',
      listener: (err: Error) => void
      ): this;

      Event emitter The defined events on documents including:

      1. close
      2. drain
      3. error
      4. finish
      5. pipe
      6. unpipe
      event: 'finish',
      listener: () => void
      ): this;

      Event emitter The defined events on documents including:

      1. close
      2. drain
      3. error
      4. finish
      5. pipe
      6. unpipe
      event: 'pipe',
      listener: (src: Readable) => void
      ): this;

      Event emitter The defined events on documents including:

      1. close
      2. drain
      3. error
      4. finish
      5. pipe
      6. unpipe
      event: 'unpipe',
      listener: (src: Readable) => void
      ): this;

      Event emitter The defined events on documents including:

      1. close
      2. drain
      3. error
      4. finish
      5. pipe
      6. unpipe
      event: string | symbol,
      listener: (...args: any[]) => void
      ): this;

      Event emitter The defined events on documents including:

      1. close
      2. drain
      3. error
      4. finish
      5. pipe
      6. unpipe
    • headers: OutgoingHttpHeaders | readonly [string, string][]
      ): void;

      Adds HTTP trailers (headers but at the end of the message) to the message.

      Trailers will only be emitted if the message is chunked encoded. If not, the trailers will be silently discarded.

      HTTP requires the Trailer header to be sent to emit trailers, with a list of header field names in its value, e.g.

      message.writeHead(200, { 'Content-Type': 'text/plain',
                               'Trailer': 'Content-MD5' });
      message.write(fileData);
      message.addTrailers({ 'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667' });
      message.end();
      

      Attempting to set a header field name or value that contains invalid characters will result in a TypeError being thrown.

    • name: string,
      value: string | readonly string[]
      ): this;

      Append a single header value to the header object.

      If the value is an array, this is equivalent to calling this method multiple times.

      If there were no previous values for the header, this is equivalent to calling outgoingMessage.setHeader(name, value).

      Depending of the value of options.uniqueHeaders when the client request or the server were created, this will end up in the header being sent multiple times or a single time with values joined using ; .

      @param name

      Header name

      @param value

      Header value

    • socket: Socket
      ): void;
    • compose<T extends ReadableStream>(
      stream: ComposeFnParam | T | Iterable<T, any, any> | AsyncIterable<T, any, any>,
      options?: { signal: AbortSignal }
      ): T;
    • cork(): void;

      The writable.cork() method forces all written data to be buffered in memory. The buffered data will be flushed when either the uncork or end methods are called.

      The primary intent of writable.cork() is to accommodate a situation in which several small chunks are written to the stream in rapid succession. Instead of immediately forwarding them to the underlying destination, writable.cork() buffers all the chunks until writable.uncork() is called, which will pass them all to writable._writev(), if present. This prevents a head-of-line blocking situation where data is being buffered while waiting for the first small chunk to be processed. However, use of writable.cork() without implementing writable._writev() may have an adverse effect on throughput.

      See also: writable.uncork(), writable._writev().

    • error?: Error
      ): this;

      Destroy the stream. Optionally emit an 'error' event, and emit a 'close' event (unless emitClose is set to false). After this call, the writable stream has ended and subsequent calls to write() or end() will result in an ERR_STREAM_DESTROYED error. This is a destructive and immediate way to destroy a stream. Previous calls to write() may not have drained, and may trigger an ERR_STREAM_DESTROYED error. Use end() instead of destroy if data should flush before close, or wait for the 'drain' event before destroying the stream.

      Once destroy() has been called any further calls will be a no-op and no further errors except from _destroy() may be emitted as 'error'.

      Implementors should not override this method, but instead implement writable._destroy().

      @param error

      Optional, an error to emit with 'error' event.

    • socket: Socket
      ): void;
    • event: 'close'
      ): boolean;

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

      Returns true if the event had listeners, false otherwise.

      import { EventEmitter } from 'node:events';
      const myEmitter = new EventEmitter();
      
      // First listener
      myEmitter.on('event', function firstListener() {
        console.log('Helloooo! first listener');
      });
      // Second listener
      myEmitter.on('event', function secondListener(arg1, arg2) {
        console.log(`event with parameters ${arg1}, ${arg2} in second listener`);
      });
      // Third listener
      myEmitter.on('event', function thirdListener(...args) {
        const parameters = args.join(', ');
        console.log(`event with parameters ${parameters} in third listener`);
      });
      
      console.log(myEmitter.listeners('event'));
      
      myEmitter.emit('event', 1, 2, 3, 4, 5);
      
      // Prints:
      // [
      //   [Function: firstListener],
      //   [Function: secondListener],
      //   [Function: thirdListener]
      // ]
      // Helloooo! first listener
      // event with parameters 1, 2 in second listener
      // event with parameters 1, 2, 3, 4, 5 in third listener
      
      event: 'drain'
      ): boolean;
      event: 'error',
      err: Error
      ): boolean;
      event: 'finish'
      ): boolean;
      event: 'pipe',
      ): boolean;
      event: 'unpipe',
      ): boolean;
      event: string | symbol,
      ...args: any[]
      ): boolean;
    • cb?: () => void
      ): this;

      Calling the writable.end() method signals that no more data will be written to the Writable. The optional chunk and encoding arguments allow one final additional chunk of data to be written immediately before closing the stream.

      Calling the write method after calling end will raise an error.

      // Write 'hello, ' and then end with 'world!'.
      import fs from 'node:fs';
      const file = fs.createWriteStream('example.txt');
      file.write('hello, ');
      file.end('world!');
      // Writing more now is not allowed!
      
      chunk: any,
      cb?: () => void
      ): this;

      Calling the writable.end() method signals that no more data will be written to the Writable. The optional chunk and encoding arguments allow one final additional chunk of data to be written immediately before closing the stream.

      Calling the write method after calling end will raise an error.

      // Write 'hello, ' and then end with 'world!'.
      import fs from 'node:fs';
      const file = fs.createWriteStream('example.txt');
      file.write('hello, ');
      file.end('world!');
      // Writing more now is not allowed!
      
      @param chunk

      Optional data to write. For streams not operating in object mode, chunk must be a {string}, {Buffer}, {TypedArray} or {DataView}. For object mode streams, chunk may be any JavaScript value other than null.

      chunk: any,
      encoding: BufferEncoding,
      cb?: () => void
      ): this;

      Calling the writable.end() method signals that no more data will be written to the Writable. The optional chunk and encoding arguments allow one final additional chunk of data to be written immediately before closing the stream.

      Calling the write method after calling end will raise an error.

      // Write 'hello, ' and then end with 'world!'.
      import fs from 'node:fs';
      const file = fs.createWriteStream('example.txt');
      file.write('hello, ');
      file.end('world!');
      // Writing more now is not allowed!
      
      @param chunk

      Optional data to write. For streams not operating in object mode, chunk must be a {string}, {Buffer}, {TypedArray} or {DataView}. For object mode streams, chunk may be any JavaScript value other than null.

      @param encoding

      The encoding if chunk is a string

    • eventNames(): string | symbol[];

      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) ]
      
    • flushHeaders(): void;

      Flushes the message headers.

      For efficiency reason, Node.js normally buffers the message headers until outgoingMessage.end() is called or the first chunk of message data is written. It then tries to pack the headers and data into a single TCP packet.

      It is usually desired (it saves a TCP round-trip), but not when the first data is not sent until possibly much later. outgoingMessage.flushHeaders() bypasses the optimization and kickstarts the message.

    • name: string
      ): undefined | string | number | string[];

      Gets the value of the HTTP header with the given name. If that header is not set, the returned value will be undefined.

      @param name

      Name of header

    • getHeaderNames(): string[];

      Returns an array containing the unique names of the current outgoing headers. All names are lowercase.

    • Returns a shallow copy of the current outgoing headers. Since a shallow copy is used, array values may be mutated without additional calls to various header-related HTTP module methods. The keys of the returned object are the header names and the values are the respective header values. All header names are lowercase.

      The object returned by the outgoingMessage.getHeaders() method does not prototypically inherit from the JavaScript Object. This means that typical Object methods such as obj.toString(), obj.hasOwnProperty(), and others are not defined and will not work.

      outgoingMessage.setHeader('Foo', 'bar');
      outgoingMessage.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);
      
      const headers = outgoingMessage.getHeaders();
      // headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] }
      
    • getMaxListeners(): number;

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

    • name: string
      ): boolean;

      Returns true if the header identified by name is currently set in the outgoing headers. The header name is case-insensitive.

      const hasContentType = outgoingMessage.hasHeader('content-type');
      
    • eventName: string | symbol,
      listener?: Function
      ): number;

      Returns the number of listeners listening for the event named eventName. If listener is provided, it will return how many times the listener is found in the list of the listeners of the event.

      @param eventName

      The name of the event being listened for

      @param listener

      The event handler function

    • eventName: string | symbol
      ): Function[];

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

      server.on('connection', (stream) => {
        console.log('someone connected!');
      });
      console.log(util.inspect(server.listeners('connection')));
      // Prints: [ [Function] ]
      
    • off<K>(
      eventName: string | symbol,
      listener: (...args: any[]) => void
      ): this;

      Alias for emitter.removeListener().

    • event: 'close',
      listener: () => void
      ): this;

      Adds the listener function to the end of the listeners array for the event named eventName. No checks are made to see if the listener has already been added. Multiple calls passing the same combination of eventName and listener will result in the listener being added, and called, multiple times.

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

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

      By default, event listeners are invoked in the order they are added. The emitter.prependListener() method can be used as an alternative to add the event listener to the beginning of the listeners array.

      import { EventEmitter } from 'node:events';
      const myEE = new EventEmitter();
      myEE.on('foo', () => console.log('a'));
      myEE.prependListener('foo', () => console.log('b'));
      myEE.emit('foo');
      // Prints:
      //   b
      //   a
      
      @param listener

      The callback function

      event: 'drain',
      listener: () => void
      ): this;
      event: 'error',
      listener: (err: Error) => void
      ): this;
      event: 'finish',
      listener: () => void
      ): this;
      event: 'pipe',
      listener: (src: Readable) => void
      ): this;
      event: 'unpipe',
      listener: (src: Readable) => void
      ): this;
      event: string | symbol,
      listener: (...args: any[]) => void
      ): this;
    • event: 'close',
      listener: () => void
      ): this;

      Adds a one-time listener function for the event named eventName. The next time eventName is triggered, this listener is removed and then invoked.

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

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

      By default, event listeners are invoked in the order they are added. The emitter.prependOnceListener() method can be used as an alternative to add the event listener to the beginning of the listeners array.

      import { EventEmitter } from 'node:events';
      const myEE = new EventEmitter();
      myEE.once('foo', () => console.log('a'));
      myEE.prependOnceListener('foo', () => console.log('b'));
      myEE.emit('foo');
      // Prints:
      //   b
      //   a
      
      @param listener

      The callback function

      event: 'drain',
      listener: () => void
      ): this;
      event: 'error',
      listener: (err: Error) => void
      ): this;
      event: 'finish',
      listener: () => void
      ): this;
      event: 'pipe',
      listener: (src: Readable) => void
      ): this;
      event: 'unpipe',
      listener: (src: Readable) => void
      ): this;
      event: string | symbol,
      listener: (...args: any[]) => void
      ): this;
    • pipe<T extends WritableStream>(
      destination: T,
      options?: { end: boolean }
      ): T;
    • event: 'close',
      listener: () => void
      ): this;

      Adds the listener function to the beginning of the listeners array for the event named eventName. No checks are made to see if the listener has already been added. Multiple calls passing the same combination of eventName and listener will result in the listener being added, and called, multiple times.

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

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

      @param listener

      The callback function

      event: 'drain',
      listener: () => void
      ): this;
      event: 'error',
      listener: (err: Error) => void
      ): this;
      event: 'finish',
      listener: () => void
      ): this;
      event: 'pipe',
      listener: (src: Readable) => void
      ): this;
      event: 'unpipe',
      listener: (src: Readable) => void
      ): this;
      event: string | symbol,
      listener: (...args: any[]) => void
      ): this;
    • event: 'close',
      listener: () => void
      ): this;

      Adds a one-timelistener function for the event named eventName to the beginning of the listeners array. The next time eventName is triggered, this listener is removed, and then invoked.

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

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

      @param listener

      The callback function

      event: 'drain',
      listener: () => void
      ): this;
      event: 'error',
      listener: (err: Error) => void
      ): this;
      event: 'finish',
      listener: () => void
      ): this;
      event: 'pipe',
      listener: (src: Readable) => void
      ): this;
      event: 'unpipe',
      listener: (src: Readable) => void
      ): this;
      event: string | symbol,
      listener: (...args: any[]) => void
      ): this;
    • eventName: string | symbol
      ): Function[];

      Returns a copy of the array of listeners for the event named eventName, including any wrappers (such as those created by .once()).

      import { EventEmitter } from 'node:events';
      const emitter = new EventEmitter();
      emitter.once('log', () => console.log('log once'));
      
      // Returns a new Array with a function `onceWrapper` which has a property
      // `listener` which contains the original listener bound above
      const listeners = emitter.rawListeners('log');
      const logFnWrapper = listeners[0];
      
      // Logs "log once" to the console and does not unbind the `once` event
      logFnWrapper.listener();
      
      // Logs "log once" to the console and removes the listener
      logFnWrapper();
      
      emitter.on('log', () => console.log('log persistently'));
      // Will return a new Array with a single function bound by `.on()` above
      const newListeners = emitter.rawListeners('log');
      
      // Logs "log persistently" twice
      newListeners[0]();
      emitter.emit('log');
      
    • eventName?: string | symbol
      ): this;

      Removes all listeners, or those of the specified eventName.

      It is bad practice to remove listeners added elsewhere in the code, particularly when the EventEmitter instance was created by some other component or module (e.g. sockets or file streams).

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

    • name: string
      ): void;

      Removes a header that is queued for implicit sending.

      outgoingMessage.removeHeader('Content-Encoding');
      
      @param name

      Header name

    • event: 'close',
      listener: () => void
      ): this;

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

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

      removeListener() will remove, at most, one instance of a listener from the listener array. If any single listener has been added multiple times to the listener array for the specified eventName, then removeListener() must be called multiple times to remove each instance.

      Once an event is emitted, all listeners attached to it at the time of emitting are called in order. This implies that any removeListener() or removeAllListeners() calls after emitting and before the last listener finishes execution will not remove them fromemit() in progress. Subsequent events behave as expected.

      import { EventEmitter } from 'node:events';
      class MyEmitter extends EventEmitter {}
      const myEmitter = new MyEmitter();
      
      const callbackA = () => {
        console.log('A');
        myEmitter.removeListener('event', callbackB);
      };
      
      const callbackB = () => {
        console.log('B');
      };
      
      myEmitter.on('event', callbackA);
      
      myEmitter.on('event', callbackB);
      
      // callbackA removes listener callbackB but it will still be called.
      // Internal listener array at time of emit [callbackA, callbackB]
      myEmitter.emit('event');
      // Prints:
      //   A
      //   B
      
      // callbackB is now removed.
      // Internal listener array [callbackA]
      myEmitter.emit('event');
      // Prints:
      //   A
      

      Because listeners are managed using an internal array, calling this will change the position indices of any listener registered after the listener being removed. This will not impact the order in which listeners are called, but it means that any copies of the listener array as returned by the emitter.listeners() method will need to be recreated.

      When a single function has been added as a handler multiple times for a single event (as in the example below), removeListener() will remove the most recently added instance. In the example the once('ping') listener is removed:

      import { EventEmitter } from 'node:events';
      const ee = new EventEmitter();
      
      function pong() {
        console.log('pong');
      }
      
      ee.on('ping', pong);
      ee.once('ping', pong);
      ee.removeListener('ping', pong);
      
      ee.emit('ping');
      ee.emit('ping');
      

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

      event: 'drain',
      listener: () => void
      ): this;
      event: 'error',
      listener: (err: Error) => void
      ): this;
      event: 'finish',
      listener: () => void
      ): this;
      event: 'pipe',
      listener: (src: Readable) => void
      ): this;
      event: 'unpipe',
      listener: (src: Readable) => void
      ): this;
      event: string | symbol,
      listener: (...args: any[]) => void
      ): this;
    • encoding: BufferEncoding
      ): this;

      The writable.setDefaultEncoding() method sets the default encoding for a Writable stream.

      @param encoding

      The new default encoding

    • name: string,
      value: string | number | readonly string[]
      ): this;

      Sets a single header value. If the header already exists in the to-be-sent headers, its value will be replaced. Use an array of strings to send multiple headers with the same name.

      @param name

      Header name

      @param value

      Header value

    • headers: Headers | Map<string, string | number | readonly string[]>
      ): this;

      Sets multiple header values for implicit headers. headers must be an instance of Headers or Map, if a header already exists in the to-be-sent headers, its value will be replaced.

      const headers = new Headers({ foo: 'bar' });
      outgoingMessage.setHeaders(headers);
      

      or

      const headers = new Map([['foo', 'bar']]);
      outgoingMessage.setHeaders(headers);
      

      When headers have been set with outgoingMessage.setHeaders(), they will be merged with any headers passed to response.writeHead(), with the headers passed to response.writeHead() given precedence.

      // Returns content-type = text/plain
      const server = http.createServer((req, res) => {
        const headers = new Headers({ 'Content-Type': 'text/html' });
        res.setHeaders(headers);
        res.writeHead(200, { 'Content-Type': 'text/plain' });
        res.end('ok');
      });
      
    • n: number
      ): this;

      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.

    • msecs: number,
      callback?: () => void
      ): this;

      Once a socket is associated with the message and is connected, socket.setTimeout() will be called with msecs as the first parameter.

      @param callback

      Optional function to be called when a timeout occurs. Same as binding to the timeout event.

    • uncork(): void;

      The writable.uncork() method flushes all data buffered since cork was called.

      When using writable.cork() and writable.uncork() to manage the buffering of writes to a stream, defer calls to writable.uncork() using process.nextTick(). Doing so allows batching of all writable.write() calls that occur within a given Node.js event loop phase.

      stream.cork();
      stream.write('some ');
      stream.write('data ');
      process.nextTick(() => stream.uncork());
      

      If the writable.cork() method is called multiple times on a stream, the same number of calls to writable.uncork() must be called to flush the buffered data.

      stream.cork();
      stream.write('some ');
      stream.cork();
      stream.write('data ');
      process.nextTick(() => {
        stream.uncork();
        // The data will not be flushed until uncork() is called a second time.
        stream.uncork();
      });
      

      See also: writable.cork().

    • chunk: any,
      callback?: (error: undefined | null | Error) => void
      ): boolean;

      The writable.write() method writes some data to the stream, and calls the supplied callback once the data has been fully handled. If an error occurs, the callback will be called with the error as its first argument. The callback is called asynchronously and before 'error' is emitted.

      The return value is true if the internal buffer is less than the highWaterMark configured when the stream was created after admitting chunk. If false is returned, further attempts to write data to the stream should stop until the 'drain' event is emitted.

      While a stream is not draining, calls to write() will buffer chunk, and return false. Once all currently buffered chunks are drained (accepted for delivery by the operating system), the 'drain' event will be emitted. Once write() returns false, do not write more chunks until the 'drain' event is emitted. While calling write() on a stream that is not draining is allowed, Node.js will buffer all written chunks until maximum memory usage occurs, at which point it will abort unconditionally. Even before it aborts, high memory usage will cause poor garbage collector performance and high RSS (which is not typically released back to the system, even after the memory is no longer required). Since TCP sockets may never drain if the remote peer does not read the data, writing a socket that is not draining may lead to a remotely exploitable vulnerability.

      Writing data while the stream is not draining is particularly problematic for a Transform, because the Transform streams are paused by default until they are piped or a 'data' or 'readable' event handler is added.

      If the data to be written can be generated or fetched on demand, it is recommended to encapsulate the logic into a Readable and use pipe. However, if calling write() is preferred, it is possible to respect backpressure and avoid memory issues using the 'drain' event:

      function write(data, cb) {
        if (!stream.write(data)) {
          stream.once('drain', cb);
        } else {
          process.nextTick(cb);
        }
      }
      
      // Wait for cb to be called before doing any other write.
      write('hello', () => {
        console.log('Write completed, do more writes now.');
      });
      

      A Writable stream in object mode will always ignore the encoding argument.

      @param chunk

      Optional data to write. For streams not operating in object mode, chunk must be a {string}, {Buffer}, {TypedArray} or {DataView}. For object mode streams, chunk may be any JavaScript value other than null.

      @param callback

      Callback for when this chunk of data is flushed.

      @returns

      false if the stream wishes for the calling code to wait for the 'drain' event to be emitted before continuing to write additional data; otherwise true.

      chunk: any,
      encoding: BufferEncoding,
      callback?: (error: undefined | null | Error) => void
      ): boolean;

      The writable.write() method writes some data to the stream, and calls the supplied callback once the data has been fully handled. If an error occurs, the callback will be called with the error as its first argument. The callback is called asynchronously and before 'error' is emitted.

      The return value is true if the internal buffer is less than the highWaterMark configured when the stream was created after admitting chunk. If false is returned, further attempts to write data to the stream should stop until the 'drain' event is emitted.

      While a stream is not draining, calls to write() will buffer chunk, and return false. Once all currently buffered chunks are drained (accepted for delivery by the operating system), the 'drain' event will be emitted. Once write() returns false, do not write more chunks until the 'drain' event is emitted. While calling write() on a stream that is not draining is allowed, Node.js will buffer all written chunks until maximum memory usage occurs, at which point it will abort unconditionally. Even before it aborts, high memory usage will cause poor garbage collector performance and high RSS (which is not typically released back to the system, even after the memory is no longer required). Since TCP sockets may never drain if the remote peer does not read the data, writing a socket that is not draining may lead to a remotely exploitable vulnerability.

      Writing data while the stream is not draining is particularly problematic for a Transform, because the Transform streams are paused by default until they are piped or a 'data' or 'readable' event handler is added.

      If the data to be written can be generated or fetched on demand, it is recommended to encapsulate the logic into a Readable and use pipe. However, if calling write() is preferred, it is possible to respect backpressure and avoid memory issues using the 'drain' event:

      function write(data, cb) {
        if (!stream.write(data)) {
          stream.once('drain', cb);
        } else {
          process.nextTick(cb);
        }
      }
      
      // Wait for cb to be called before doing any other write.
      write('hello', () => {
        console.log('Write completed, do more writes now.');
      });
      

      A Writable stream in object mode will always ignore the encoding argument.

      @param chunk

      Optional data to write. For streams not operating in object mode, chunk must be a {string}, {Buffer}, {TypedArray} or {DataView}. For object mode streams, chunk may be any JavaScript value other than null.

      @param encoding

      The encoding, if chunk is a string.

      @param callback

      Callback for when this chunk of data is flushed.

      @returns

      false if the stream wishes for the calling code to wait for the 'drain' event to be emitted before continuing to write additional data; otherwise true.

    • callback?: () => void
      ): void;

      Sends an HTTP/1.1 100 Continue message to the client, indicating that the request body should be sent. See the 'checkContinue' event on Server.

    • hints: Record<string, string | string[]>,
      callback?: () => void
      ): void;

      Sends an HTTP/1.1 103 Early Hints message to the client with a Link header, indicating that the user agent can preload/preconnect the linked resources. The hints is an object containing the values of headers to be sent with early hints message. The optional callback argument will be called when the response message has been written.

      Example

      const earlyHintsLink = '</styles.css>; rel=preload; as=style';
      response.writeEarlyHints({
        'link': earlyHintsLink,
      });
      
      const earlyHintsLinks = [
        '</styles.css>; rel=preload; as=style',
        '</scripts.js>; rel=preload; as=script',
      ];
      response.writeEarlyHints({
        'link': earlyHintsLinks,
        'x-trace-id': 'id for diagnostics',
      });
      
      const earlyHintsCallback = () => console.log('early hints message sent');
      response.writeEarlyHints({
        'link': earlyHintsLinks,
      }, earlyHintsCallback);
      
      @param hints

      An object containing the values of headers

      @param callback

      Will be called when the response message has been written

    • statusCode: number,
      statusMessage?: string,
      ): this;

      Sends a response header to the request. The status code is a 3-digit HTTP status code, like 404. The last argument, headers, are the response headers. Optionally one can give a human-readable statusMessage as the second argument.

      headers may be an Array where the keys and values are in the same list. It is not a list of tuples. So, the even-numbered offsets are key values, and the odd-numbered offsets are the associated values. The array is in the same format as request.rawHeaders.

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

      const body = 'hello world';
      response
        .writeHead(200, {
          'Content-Length': Buffer.byteLength(body),
          'Content-Type': 'text/plain',
        })
        .end(body);
      

      This method must only be called once on a message and it must be called before response.end() is called.

      If response.write() or response.end() are called before calling this, the implicit/mutable headers will be calculated and call this function.

      When headers have been set with response.setHeader(), they will be merged with any headers passed to response.writeHead(), with the headers passed to response.writeHead() given precedence.

      If this method is called and response.setHeader() has not been called, it will directly write the supplied header values onto the network channel without caching internally, and the response.getHeader() on the header will not yield the expected result. If progressive population of headers is desired with potential future retrieval and modification, use response.setHeader() instead.

      // Returns content-type = text/plain
      const server = http.createServer((req, res) => {
        res.setHeader('Content-Type', 'text/html');
        res.setHeader('X-Foo', 'bar');
        res.writeHead(200, { 'Content-Type': 'text/plain' });
        res.end('ok');
      });
      

      Content-Length is read in bytes, not characters. Use Buffer.byteLength() to determine the length of the body in bytes. Node.js will check whether Content-Length and the length of the body which has been transmitted are equal or not.

      Attempting to set a header field name or value that contains invalid characters will result in a [Error][] being thrown.

      statusCode: number,
      ): this;

      Sends a response header to the request. The status code is a 3-digit HTTP status code, like 404. The last argument, headers, are the response headers. Optionally one can give a human-readable statusMessage as the second argument.

      headers may be an Array where the keys and values are in the same list. It is not a list of tuples. So, the even-numbered offsets are key values, and the odd-numbered offsets are the associated values. The array is in the same format as request.rawHeaders.

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

      const body = 'hello world';
      response
        .writeHead(200, {
          'Content-Length': Buffer.byteLength(body),
          'Content-Type': 'text/plain',
        })
        .end(body);
      

      This method must only be called once on a message and it must be called before response.end() is called.

      If response.write() or response.end() are called before calling this, the implicit/mutable headers will be calculated and call this function.

      When headers have been set with response.setHeader(), they will be merged with any headers passed to response.writeHead(), with the headers passed to response.writeHead() given precedence.

      If this method is called and response.setHeader() has not been called, it will directly write the supplied header values onto the network channel without caching internally, and the response.getHeader() on the header will not yield the expected result. If progressive population of headers is desired with potential future retrieval and modification, use response.setHeader() instead.

      // Returns content-type = text/plain
      const server = http.createServer((req, res) => {
        res.setHeader('Content-Type', 'text/html');
        res.setHeader('X-Foo', 'bar');
        res.writeHead(200, { 'Content-Type': 'text/plain' });
        res.end('ok');
      });
      

      Content-Length is read in bytes, not characters. Use Buffer.byteLength() to determine the length of the body in bytes. Node.js will check whether Content-Length and the length of the body which has been transmitted are equal or not.

      Attempting to set a header field name or value that contains invalid characters will result in a [Error][] being thrown.

    • Sends a HTTP/1.1 102 Processing message to the client, indicating that the request body should be sent.

    • signal: AbortSignal,
      resource: (event: Event) => void
      ): Disposable;

      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]();
        }
      }
      
      @returns

      Disposable that removes the abort listener.

    • static fromWeb(
      writableStream: WritableStream,
      options?: Pick<WritableOptions<Writable>, 'signal' | 'decodeStrings' | 'highWaterMark' | 'objectMode'>

      A utility method for creating a Writable from a web WritableStream.

    • emitter: EventEmitter<DefaultEventMap> | EventTarget,
      name: string | symbol
      ): Function[];

      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] ]
      }
      
    • emitter: EventEmitter<DefaultEventMap> | EventTarget
      ): number;

      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
      }
      
    • static on(
      emitter: EventEmitter,
      eventName: string | symbol,
      options?: StaticEventEmitterIteratorOptions
      ): AsyncIterator<any[]>;
      import { on, EventEmitter } from 'node:events';
      import process from 'node:process';
      
      const ee = new EventEmitter();
      
      // Emit later on
      process.nextTick(() => {
        ee.emit('foo', 'bar');
        ee.emit('foo', 42);
      });
      
      for await (const event of on(ee, 'foo')) {
        // The execution of this inner block is synchronous and it
        // processes one event at a time (even with await). Do not use
        // if concurrent execution is required.
        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:

      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 on
      process.nextTick(() => {
        ee.emit('foo', 'bar');
        ee.emit('foo', 42);
        ee.emit('close');
      });
      
      for await (const event of on(ee, 'foo', { close: ['close'] })) {
        console.log(event); // prints ['bar'] [42]
      }
      // the loop will exit after 'close' is emitted
      console.log('done'); // prints 'done'
      
      @returns

      An AsyncIterator that iterates eventName events emitted by the emitter

      static on(
      emitter: EventTarget,
      eventName: string,
      options?: StaticEventEmitterIteratorOptions
      ): AsyncIterator<any[]>;
      import { on, EventEmitter } from 'node:events';
      import process from 'node:process';
      
      const ee = new EventEmitter();
      
      // Emit later on
      process.nextTick(() => {
        ee.emit('foo', 'bar');
        ee.emit('foo', 42);
      });
      
      for await (const event of on(ee, 'foo')) {
        // The execution of this inner block is synchronous and it
        // processes one event at a time (even with await). Do not use
        // if concurrent execution is required.
        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:

      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 on
      process.nextTick(() => {
        ee.emit('foo', 'bar');
        ee.emit('foo', 42);
        ee.emit('close');
      });
      
      for await (const event of on(ee, 'foo', { close: ['close'] })) {
        console.log(event); // prints ['bar'] [42]
      }
      // the loop will exit after 'close' is emitted
      console.log('done'); // prints 'done'
      
      @returns

      An AsyncIterator that iterates eventName events emitted by the emitter

    • static once(
      emitter: EventEmitter,
      eventName: string | symbol,
      options?: StaticEventEmitterOptions
      ): Promise<any[]>;

      Creates a Promise that is fulfilled when the EventEmitter emits the given event or that is rejected if the EventEmitter emits 'error' while waiting. The Promise will resolve with an array of all the arguments emitted to the given event.

      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 boom
      

      An 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 event
      ee.emit('foo'); // Prints: Waiting for the event was canceled!
      
      static once(
      emitter: EventTarget,
      eventName: string,
      options?: StaticEventEmitterOptions
      ): Promise<any[]>;

      Creates a Promise that is fulfilled when the EventEmitter emits the given event or that is rejected if the EventEmitter emits 'error' while waiting. The Promise will resolve with an array of all the arguments emitted to the given event.

      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 boom
      

      An 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 event
      ee.emit('foo'); // Prints: Waiting for the event was canceled!
      
    • n?: number,
      ...eventTargets: EventEmitter<DefaultEventMap> | EventTarget[]
      ): void;
      import { setMaxListeners, EventEmitter } from 'node:events';
      
      const target = new EventTarget();
      const emitter = new EventEmitter();
      
      setMaxListeners(5, target, emitter);
      
      @param n

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

      @param eventTargets

      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.

    • static toWeb(
      streamWritable: Writable

      A utility method for creating a web WritableStream from a Writable.

  • const CloseEvent: CloseEvent
  • Global instance of Agent which is used as the default for all HTTP client requests. Diverges from a default Agent configuration by having keepAlive enabled and a timeout of 5 seconds.

  • const maxHeaderSize: number

    Read-only property specifying the maximum allowed size of HTTP headers in bytes. Defaults to 16KB. Configurable using the --max-http-header-size CLI option.

  • const MessageEvent: MessageEvent
  • const METHODS: string[]
  • const STATUS_CODES: {
    __index[
    errorCode: number
    ]: undefined | string;
    __index[
    errorCode: string
    ]: undefined | string;
    }
  • const WebSocket: WebSocket

    A browser-compatible implementation of WebSocket.

  • function createServer<Request extends typeof IncomingMessage = typeof IncomingMessage, Response extends typeof ServerResponse = typeof ServerResponse>(
    requestListener?: RequestListener<Request, Response>
    ): Server<Request, Response>;

    Returns a new instance of Server.

    The requestListener is a function which is automatically added to the 'request' event.

    import http from 'node:http';
    
    // Create a local server to receive data from
    const server = http.createServer((req, res) => {
      res.writeHead(200, { 'Content-Type': 'application/json' });
      res.end(JSON.stringify({
        data: 'Hello World!',
      }));
    });
    
    server.listen(8000);
    
    import http from 'node:http';
    
    // Create a local server to receive data from
    const server = http.createServer();
    
    // Listen to the request event
    server.on('request', (request, res) => {
      res.writeHead(200, { 'Content-Type': 'application/json' });
      res.end(JSON.stringify({
        data: 'Hello World!',
      }));
    });
    
    server.listen(8000);
    
    function createServer<Request extends typeof IncomingMessage = typeof IncomingMessage, Response extends typeof ServerResponse = typeof ServerResponse>(
    options: ServerOptions<Request, Response>,
    requestListener?: RequestListener<Request, Response>
    ): Server<Request, Response>;

    Returns a new instance of Server.

    The requestListener is a function which is automatically added to the 'request' event.

    import http from 'node:http';
    
    // Create a local server to receive data from
    const server = http.createServer((req, res) => {
      res.writeHead(200, { 'Content-Type': 'application/json' });
      res.end(JSON.stringify({
        data: 'Hello World!',
      }));
    });
    
    server.listen(8000);
    
    import http from 'node:http';
    
    // Create a local server to receive data from
    const server = http.createServer();
    
    // Listen to the request event
    server.on('request', (request, res) => {
      res.writeHead(200, { 'Content-Type': 'application/json' });
      res.end(JSON.stringify({
        data: 'Hello World!',
      }));
    });
    
    server.listen(8000);
    
  • function get(
    options: string | URL | RequestOptions,
    callback?: (res: IncomingMessage) => void

    Since most requests are GET requests without bodies, Node.js provides this convenience method. The only difference between this method and request is that it sets the method to GET by default and calls req.end() automatically. The callback must take care to consume the response data for reasons stated in ClientRequest section.

    The callback is invoked with a single argument that is an instance of IncomingMessage.

    JSON fetching example:

    http.get('http://localhost:8000/', (res) => {
      const { statusCode } = res;
      const contentType = res.headers['content-type'];
    
      let error;
      // Any 2xx status code signals a successful response but
      // here we're only checking for 200.
      if (statusCode !== 200) {
        error = new Error('Request Failed.\n' +
                          `Status Code: ${statusCode}`);
      } else if (!/^application/json/.test(contentType)) {
        error = new Error('Invalid content-type.\n' +
                          `Expected application/json but received ${contentType}`);
      }
      if (error) {
        console.error(error.message);
        // Consume response data to free up memory
        res.resume();
        return;
      }
    
      res.setEncoding('utf8');
      let rawData = '';
      res.on('data', (chunk) => { rawData += chunk; });
      res.on('end', () => {
        try {
          const parsedData = JSON.parse(rawData);
          console.log(parsedData);
        } catch (e) {
          console.error(e.message);
        }
      });
    }).on('error', (e) => {
      console.error(`Got error: ${e.message}`);
    });
    
    // Create a local server to receive data from
    const server = http.createServer((req, res) => {
      res.writeHead(200, { 'Content-Type': 'application/json' });
      res.end(JSON.stringify({
        data: 'Hello World!',
      }));
    });
    
    server.listen(8000);
    
    @param options

    Accepts the same options as request, with the method set to GET by default.

    function get(
    url: string | URL,
    options: RequestOptions,
    callback?: (res: IncomingMessage) => void

    Since most requests are GET requests without bodies, Node.js provides this convenience method. The only difference between this method and request is that it sets the method to GET by default and calls req.end() automatically. The callback must take care to consume the response data for reasons stated in ClientRequest section.

    The callback is invoked with a single argument that is an instance of IncomingMessage.

    JSON fetching example:

    http.get('http://localhost:8000/', (res) => {
      const { statusCode } = res;
      const contentType = res.headers['content-type'];
    
      let error;
      // Any 2xx status code signals a successful response but
      // here we're only checking for 200.
      if (statusCode !== 200) {
        error = new Error('Request Failed.\n' +
                          `Status Code: ${statusCode}`);
      } else if (!/^application/json/.test(contentType)) {
        error = new Error('Invalid content-type.\n' +
                          `Expected application/json but received ${contentType}`);
      }
      if (error) {
        console.error(error.message);
        // Consume response data to free up memory
        res.resume();
        return;
      }
    
      res.setEncoding('utf8');
      let rawData = '';
      res.on('data', (chunk) => { rawData += chunk; });
      res.on('end', () => {
        try {
          const parsedData = JSON.parse(rawData);
          console.log(parsedData);
        } catch (e) {
          console.error(e.message);
        }
      });
    }).on('error', (e) => {
      console.error(`Got error: ${e.message}`);
    });
    
    // Create a local server to receive data from
    const server = http.createServer((req, res) => {
      res.writeHead(200, { 'Content-Type': 'application/json' });
      res.end(JSON.stringify({
        data: 'Hello World!',
      }));
    });
    
    server.listen(8000);
    
    @param options

    Accepts the same options as request, with the method set to GET by default.

  • function request(
    options: string | URL | RequestOptions,
    callback?: (res: IncomingMessage) => void

    options in socket.connect() are also supported.

    Node.js maintains several connections per server to make HTTP requests. This function allows one to transparently issue requests.

    url can be a string or a URL object. If url is a string, it is automatically parsed with new URL(). If it is a URL object, it will be automatically converted to an ordinary options object.

    If both url and options are specified, the objects are merged, with the options properties taking precedence.

    The optional callback parameter will be added as a one-time listener for the 'response' event.

    http.request() returns an instance of the ClientRequest class. The ClientRequest instance is a writable stream. If one needs to upload a file with a POST request, then write to the ClientRequest object.

    import http from 'node:http';
    import { Buffer } from 'node:buffer';
    
    const postData = JSON.stringify({
      'msg': 'Hello World!',
    });
    
    const options = {
      hostname: 'www.google.com',
      port: 80,
      path: '/upload',
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Content-Length': Buffer.byteLength(postData),
      },
    };
    
    const req = http.request(options, (res) => {
      console.log(`STATUS: ${res.statusCode}`);
      console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
      res.setEncoding('utf8');
      res.on('data', (chunk) => {
        console.log(`BODY: ${chunk}`);
      });
      res.on('end', () => {
        console.log('No more data in response.');
      });
    });
    
    req.on('error', (e) => {
      console.error(`problem with request: ${e.message}`);
    });
    
    // Write data to request body
    req.write(postData);
    req.end();
    

    In the example req.end() was called. With http.request() one must always call req.end() to signify the end of the request - even if there is no data being written to the request body.

    If any error is encountered during the request (be that with DNS resolution, TCP level errors, or actual HTTP parse errors) an 'error' event is emitted on the returned request object. As with all 'error' events, if no listeners are registered the error will be thrown.

    There are a few special headers that should be noted.

    • Sending a 'Connection: keep-alive' will notify Node.js that the connection to the server should be persisted until the next request.
    • Sending a 'Content-Length' header will disable the default chunked encoding.
    • Sending an 'Expect' header will immediately send the request headers. Usually, when sending 'Expect: 100-continue', both a timeout and a listener for the 'continue' event should be set. See RFC 2616 Section 8.2.3 for more information.
    • Sending an Authorization header will override using the auth option to compute basic authentication.

    Example using a URL as options:

    const options = new URL('http://abc:xyz@example.com');
    
    const req = http.request(options, (res) => {
      // ...
    });
    

    In a successful request, the following events will be emitted in the following order:

    • 'socket'
    • 'response'
      • 'data' any number of times, on the res object ('data' will not be emitted at all if the response body is empty, for instance, in most redirects)
      • 'end' on the res object
    • 'close'

    In the case of a connection error, the following events will be emitted:

    • 'socket'
    • 'error'
    • 'close'

    In the case of a premature connection close before the response is received, the following events will be emitted in the following order:

    • 'socket'
    • 'error' with an error with message 'Error: socket hang up' and code 'ECONNRESET'
    • 'close'

    In the case of a premature connection close after the response is received, the following events will be emitted in the following order:

    • 'socket'
    • 'response'
      • 'data' any number of times, on the res object
    • (connection closed here)
    • 'aborted' on the res object
    • 'close'
    • 'error' on the res object with an error with message 'Error: aborted' and code 'ECONNRESET'
    • 'close' on the res object

    If req.destroy() is called before a socket is assigned, the following events will be emitted in the following order:

    • (req.destroy() called here)
    • 'error' with an error with message 'Error: socket hang up' and code 'ECONNRESET', or the error with which req.destroy() was called
    • 'close'

    If req.destroy() is called before the connection succeeds, the following events will be emitted in the following order:

    • 'socket'
    • (req.destroy() called here)
    • 'error' with an error with message 'Error: socket hang up' and code 'ECONNRESET', or the error with which req.destroy() was called
    • 'close'

    If req.destroy() is called after the response is received, the following events will be emitted in the following order:

    • 'socket'
    • 'response'
      • 'data' any number of times, on the res object
    • (req.destroy() called here)
    • 'aborted' on the res object
    • 'close'
    • 'error' on the res object with an error with message 'Error: aborted' and code 'ECONNRESET', or the error with which req.destroy() was called
    • 'close' on the res object

    If req.abort() is called before a socket is assigned, the following events will be emitted in the following order:

    • (req.abort() called here)
    • 'abort'
    • 'close'

    If req.abort() is called before the connection succeeds, the following events will be emitted in the following order:

    • 'socket'
    • (req.abort() called here)
    • 'abort'
    • 'error' with an error with message 'Error: socket hang up' and code 'ECONNRESET'
    • 'close'

    If req.abort() is called after the response is received, the following events will be emitted in the following order:

    • 'socket'
    • 'response'
      • 'data' any number of times, on the res object
    • (req.abort() called here)
    • 'abort'
    • 'aborted' on the res object
    • 'error' on the res object with an error with message 'Error: aborted' and code 'ECONNRESET'.
    • 'close'
    • 'close' on the res object

    Setting the timeout option or using the setTimeout() function will not abort the request or do anything besides add a 'timeout' event.

    Passing an AbortSignal and then calling abort() on the corresponding AbortController will behave the same way as calling .destroy() on the request. Specifically, the 'error' event will be emitted with an error with the message 'AbortError: The operation was aborted', the code 'ABORT_ERR' and the cause, if one was provided.

    function request(
    url: string | URL,
    options: RequestOptions,
    callback?: (res: IncomingMessage) => void

    options in socket.connect() are also supported.

    Node.js maintains several connections per server to make HTTP requests. This function allows one to transparently issue requests.

    url can be a string or a URL object. If url is a string, it is automatically parsed with new URL(). If it is a URL object, it will be automatically converted to an ordinary options object.

    If both url and options are specified, the objects are merged, with the options properties taking precedence.

    The optional callback parameter will be added as a one-time listener for the 'response' event.

    http.request() returns an instance of the ClientRequest class. The ClientRequest instance is a writable stream. If one needs to upload a file with a POST request, then write to the ClientRequest object.

    import http from 'node:http';
    import { Buffer } from 'node:buffer';
    
    const postData = JSON.stringify({
      'msg': 'Hello World!',
    });
    
    const options = {
      hostname: 'www.google.com',
      port: 80,
      path: '/upload',
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Content-Length': Buffer.byteLength(postData),
      },
    };
    
    const req = http.request(options, (res) => {
      console.log(`STATUS: ${res.statusCode}`);
      console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
      res.setEncoding('utf8');
      res.on('data', (chunk) => {
        console.log(`BODY: ${chunk}`);
      });
      res.on('end', () => {
        console.log('No more data in response.');
      });
    });
    
    req.on('error', (e) => {
      console.error(`problem with request: ${e.message}`);
    });
    
    // Write data to request body
    req.write(postData);
    req.end();
    

    In the example req.end() was called. With http.request() one must always call req.end() to signify the end of the request - even if there is no data being written to the request body.

    If any error is encountered during the request (be that with DNS resolution, TCP level errors, or actual HTTP parse errors) an 'error' event is emitted on the returned request object. As with all 'error' events, if no listeners are registered the error will be thrown.

    There are a few special headers that should be noted.

    • Sending a 'Connection: keep-alive' will notify Node.js that the connection to the server should be persisted until the next request.
    • Sending a 'Content-Length' header will disable the default chunked encoding.
    • Sending an 'Expect' header will immediately send the request headers. Usually, when sending 'Expect: 100-continue', both a timeout and a listener for the 'continue' event should be set. See RFC 2616 Section 8.2.3 for more information.
    • Sending an Authorization header will override using the auth option to compute basic authentication.

    Example using a URL as options:

    const options = new URL('http://abc:xyz@example.com');
    
    const req = http.request(options, (res) => {
      // ...
    });
    

    In a successful request, the following events will be emitted in the following order:

    • 'socket'
    • 'response'
      • 'data' any number of times, on the res object ('data' will not be emitted at all if the response body is empty, for instance, in most redirects)
      • 'end' on the res object
    • 'close'

    In the case of a connection error, the following events will be emitted:

    • 'socket'
    • 'error'
    • 'close'

    In the case of a premature connection close before the response is received, the following events will be emitted in the following order:

    • 'socket'
    • 'error' with an error with message 'Error: socket hang up' and code 'ECONNRESET'
    • 'close'

    In the case of a premature connection close after the response is received, the following events will be emitted in the following order:

    • 'socket'
    • 'response'
      • 'data' any number of times, on the res object
    • (connection closed here)
    • 'aborted' on the res object
    • 'close'
    • 'error' on the res object with an error with message 'Error: aborted' and code 'ECONNRESET'
    • 'close' on the res object

    If req.destroy() is called before a socket is assigned, the following events will be emitted in the following order:

    • (req.destroy() called here)
    • 'error' with an error with message 'Error: socket hang up' and code 'ECONNRESET', or the error with which req.destroy() was called
    • 'close'

    If req.destroy() is called before the connection succeeds, the following events will be emitted in the following order:

    • 'socket'
    • (req.destroy() called here)
    • 'error' with an error with message 'Error: socket hang up' and code 'ECONNRESET', or the error with which req.destroy() was called
    • 'close'

    If req.destroy() is called after the response is received, the following events will be emitted in the following order:

    • 'socket'
    • 'response'
      • 'data' any number of times, on the res object
    • (req.destroy() called here)
    • 'aborted' on the res object
    • 'close'
    • 'error' on the res object with an error with message 'Error: aborted' and code 'ECONNRESET', or the error with which req.destroy() was called
    • 'close' on the res object

    If req.abort() is called before a socket is assigned, the following events will be emitted in the following order:

    • (req.abort() called here)
    • 'abort'
    • 'close'

    If req.abort() is called before the connection succeeds, the following events will be emitted in the following order:

    • 'socket'
    • (req.abort() called here)
    • 'abort'
    • 'error' with an error with message 'Error: socket hang up' and code 'ECONNRESET'
    • 'close'

    If req.abort() is called after the response is received, the following events will be emitted in the following order:

    • 'socket'
    • 'response'
      • 'data' any number of times, on the res object
    • (req.abort() called here)
    • 'abort'
    • 'aborted' on the res object
    • 'error' on the res object with an error with message 'Error: aborted' and code 'ECONNRESET'.
    • 'close'
    • 'close' on the res object

    Setting the timeout option or using the setTimeout() function will not abort the request or do anything besides add a 'timeout' event.

    Passing an AbortSignal and then calling abort() on the corresponding AbortController will behave the same way as calling .destroy() on the request. Specifically, the 'error' event will be emitted with an error with the message 'AbortError: The operation was aborted', the code 'ABORT_ERR' and the cause, if one was provided.

  • max?: number
    ): void;

    Set the maximum number of idle HTTP parsers.

  • name: string
    ): void;

    Performs the low-level validations on the provided name that are done when res.setHeader(name, value) is called.

    Passing illegal value as name will result in a TypeError being thrown, identified by code: 'ERR_INVALID_HTTP_TOKEN'.

    It is not necessary to use this method before passing headers to an HTTP request or response. The HTTP module will automatically validate such headers.

    Example:

    import { validateHeaderName } from 'node:http';
    
    try {
      validateHeaderName('');
    } catch (err) {
      console.error(err instanceof TypeError); // --> true
      console.error(err.code); // --> 'ERR_INVALID_HTTP_TOKEN'
      console.error(err.message); // --> 'Header name must be a valid HTTP token [""]'
    }
    
  • name: string,
    value: string
    ): void;

    Performs the low-level validations on the provided value that are done when res.setHeader(name, value) is called.

    Passing illegal value as value will result in a TypeError being thrown.

    • Undefined value error is identified by code: 'ERR_HTTP_INVALID_HEADER_VALUE'.
    • Invalid value character error is identified by code: 'ERR_INVALID_CHAR'.

    It is not necessary to use this method before passing headers to an HTTP request or response. The HTTP module will automatically validate such headers.

    Examples:

    import { validateHeaderValue } from 'node:http';
    
    try {
      validateHeaderValue('x-my-header', undefined);
    } catch (err) {
      console.error(err instanceof TypeError); // --> true
      console.error(err.code === 'ERR_HTTP_INVALID_HEADER_VALUE'); // --> true
      console.error(err.message); // --> 'Invalid value "undefined" for header "x-my-header"'
    }
    
    try {
      validateHeaderValue('x-my-header', 'oʊmɪɡə');
    } catch (err) {
      console.error(err instanceof TypeError); // --> true
      console.error(err.code === 'ERR_INVALID_CHAR'); // --> true
      console.error(err.message); // --> 'Invalid character in header content ["x-my-header"]'
    }
    
    @param name

    Header name

    @param value

    Header value

Type definitions