net/promises API
History
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
netPromises.connect(port, host?): Promise
Objectnet.connect(). May
include a signal AbortSignal that can be used to abort an in-progress
connection attempt.Promisenet.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();
netPromises.listen(options?): Promise
Objectnet.createServer() and
server.listen(), plus:Function'connection' event.AbortSignalAbortSignal 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().Promisenet.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);