On this page

net/promises API

History
Stability: 1Experimental

The net/promises API provides a set of net functions that return Promise objects rather than relying on events. The API is accessible via require('node:net').promises or require('node:net/promises').

netPromises.connect(options): void
netPromises.connect(path): void
M

netPromises.connect

History
netPromises.connect(port, host?): Promise
Attributes
options:Object
Accepts the same arguments as net.connect(). May include a signal AbortSignal that can be used to abort an in-progress connection attempt.
Returns:Promise
Fulfills with a connected net.Socket.

A promise-based alternative to net.connect(). The returned promise is fulfilled with the socket once its 'connect' event fires, and is rejected if the connection fails or the signal is aborted. When the promise rejects, the underlying socket is destroyed.

This API is named for the action it performs and awaits — connecting — to parallel netPromises.listen(). It is not named createConnection(), because that name belongs to the socket-factory taxonomy of the callback API, which has no counterpart here.

import { connect } from 'node:net/promises';

const socket = await connect({ port: 8124 });
socket.write('hello world!');
socket.end();
M

netPromises.listen

History
netPromises.listen(options?): Promise
Attributes
options:Object
Accepts the same options as net.createServer() and server.listen(), plus:
connectionListener:Function
Automatically set as a listener for the 'connection' event.
An AbortSignal that may be used to abort the server. Aborting before the server is listening rejects the returned promise with an AbortError; aborting at any later point closes the server, matching the signal option of server.listen().
Returns:Promise
Fulfills with a listening net.Server.

Creates a net.Server and begins listening. The returned promise is fulfilled with the server once its 'listening' event fires, and is rejected if the server fails to bind or the signal is aborted before it is listening. When the promise rejects, the server is closed.

The resolved server is async iterable, so incoming connections can be consumed with for await...of (see server[Symbol.asyncIterator]()).

import { listen } from 'node:net/promises';

const server = await listen({ port: 8124 });
console.log('listening on', server.address().port);