Skip to content

Commit ab5b8e9

Browse files
net: add experimental net/promises API
Add an experimental `net/promises` namespace, accessible via `require('node:net/promises')` or `net.promises`, mirroring the existing `fs/promises` and `dns/promises` modules. It provides promise-based variants of net's one-shot lifecycle operations: - `connect()` returns a promise that fulfills with a connected Socket once the 'connect' event fires, and rejects on connection failure or when an optional AbortSignal is aborted, destroying the socket. - `listen()` creates a server, begins listening, and returns a promise that fulfills with the listening Server once the 'listening' event fires. It rejects if the server fails to bind or an optional AbortSignal is aborted, closing the server. The functions are named for the actions they await, forming a parallel `connect()`/`listen()` pair. This is intentionally not the callback API's factory taxonomy: there `createConnection()` is canonical because it both creates a socket and initiates connecting, whereas `createServer()` is a pure factory that does not listen. A `createConnection`/`createServer` pairing would be inconsistent here because `createServer` has no completion to await, so no `createConnection` alias is provided. Refs: nodejs#21482 Assisted-by: Claude Opus 4.8 <[email protected]> Signed-off-by: Ethan Arrowood <[email protected]>
1 parent ace91de commit ab5b8e9

6 files changed

Lines changed: 281 additions & 0 deletions

File tree

‎doc/api/net.md‎

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2241,6 +2241,77 @@ net.isIPv6('::1'); // returns true
22412241
net.isIPv6('fhqwhgads'); // returns false
22422242
```
22432243

2244+
## `net/promises` API
2245+
2246+
<!-- YAML
2247+
added: REPLACEME
2248+
-->
2249+
2250+
> Stability: 1 - Experimental
2251+
2252+
The `net/promises` API provides a set of `net` functions that return `Promise`
2253+
objects rather than relying on events. The API is accessible via
2254+
`require('node:net').promises` or `require('node:net/promises')`.
2255+
2256+
### `netPromises.connect(options)`
2257+
2258+
### `netPromises.connect(path)`
2259+
2260+
### `netPromises.connect(port[, host])`
2261+
2262+
<!-- YAML
2263+
added: REPLACEME
2264+
-->
2265+
2266+
* `options` {Object} Accepts the same arguments as [`net.connect()`][]. May
2267+
include a `signal` {AbortSignal} that can be used to abort an in-progress
2268+
connection attempt.
2269+
* Returns: {Promise} Fulfills with a connected [`net.Socket`][].
2270+
2271+
A promise-based alternative to [`net.connect()`][]. The returned promise is
2272+
fulfilled with the socket once its [`'connect'`][] event fires, and is rejected
2273+
if the connection fails or the `signal` is aborted. When the promise rejects,
2274+
the underlying socket is destroyed.
2275+
2276+
This API is named for the action it performs and awaits — connecting — to
2277+
parallel [`netPromises.listen()`][]. It is not named `createConnection()`,
2278+
because that name belongs to the socket-factory taxonomy of the callback API,
2279+
which has no counterpart here.
2280+
2281+
```mjs
2282+
import { connect } from 'node:net/promises';
2283+
2284+
const socket = await connect({ port: 8124 });
2285+
socket.write('hello world!');
2286+
socket.end();
2287+
```
2288+
2289+
### `netPromises.listen([options])`
2290+
2291+
<!-- YAML
2292+
added: REPLACEME
2293+
-->
2294+
2295+
* `options` {Object} Accepts the same options as [`net.createServer()`][] and
2296+
[`server.listen()`][], plus:
2297+
* `connectionListener` {Function} Automatically set as a listener for the
2298+
[`'connection'`][] event.
2299+
* `signal` {AbortSignal} An `AbortSignal` that may be used to abort the
2300+
listening server.
2301+
* Returns: {Promise} Fulfills with a listening [`net.Server`][].
2302+
2303+
Creates a [`net.Server`][] and begins listening. The returned promise is
2304+
fulfilled with the server once its [`'listening'`][] event fires, and is
2305+
rejected if the server fails to bind or the `signal` is aborted. When the
2306+
promise rejects, the server is closed.
2307+
2308+
```mjs
2309+
import { listen } from 'node:net/promises';
2310+
2311+
const server = await listen({ port: 8124 });
2312+
console.log('server bound to', server.address().port);
2313+
```
2314+
22442315
[IPC]: #ipc-support
22452316
[Identifying paths for IPC connections]: #identifying-paths-for-ipc-connections
22462317
[RFC 8305]: https://www.rfc-editor.org/rfc/rfc8305.txt
@@ -2274,6 +2345,7 @@ net.isIPv6('fhqwhgads'); // returns false
22742345
[`net.createServer()`]: #netcreateserveroptions-connectionlistener
22752346
[`net.getDefaultAutoSelectFamily()`]: #netgetdefaultautoselectfamily
22762347
[`net.getDefaultAutoSelectFamilyAttemptTimeout()`]: #netgetdefaultautoselectfamilyattempttimeout
2348+
[`netPromises.listen()`]: #netpromiseslistenoptions
22772349
[`new net.Socket(options)`]: #new-netsocketoptions
22782350
[`readable.setEncoding()`]: stream.md#readablesetencodingencoding
22792351
[`server.address()`]: #serveraddress

‎lib/internal/net/promises.js‎

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
'use strict';
2+
3+
const { once } = require('events');
4+
const {
5+
validateAbortSignal,
6+
validateObject,
7+
} = require('internal/validators');
8+
const { AbortError } = require('internal/errors');
9+
const { kEmptyObject } = require('internal/util');
10+
11+
// Lazily loaded to avoid a require cycle with the `net` module, which exposes
12+
// this namespace through its `promises` getter.
13+
let net;
14+
function lazyNet() {
15+
net ??= require('net');
16+
return net;
17+
}
18+
19+
// Resolves with a connected `net.Socket` once the `'connect'` event fires, and
20+
// rejects if the connection fails or the optional `signal` is aborted.
21+
async function connect(...args) {
22+
const lazy = lazyNet();
23+
const options = lazy._normalizeArgs(args)[0];
24+
const { signal } = options;
25+
if (signal !== undefined) {
26+
validateAbortSignal(signal, 'options.signal');
27+
if (signal.aborted) {
28+
throw new AbortError(undefined, { cause: signal.reason });
29+
}
30+
}
31+
32+
// Strip the signal so the socket does not also install its own abort
33+
// handling; rejecting and destroying below fully tears the socket down.
34+
const socket = lazy.connect({ ...options, signal: undefined });
35+
36+
try {
37+
await once(socket, 'connect', signal !== undefined ? { signal } : kEmptyObject);
38+
} catch (err) {
39+
socket.destroy();
40+
throw err;
41+
}
42+
return socket;
43+
}
44+
45+
// Creates a server and resolves with it once it is listening, rejecting if it
46+
// fails to bind or the optional `signal` is aborted.
47+
async function listen(options = kEmptyObject) {
48+
validateObject(options, 'options');
49+
const { signal, connectionListener } = options;
50+
if (signal !== undefined) {
51+
validateAbortSignal(signal, 'options.signal');
52+
if (signal.aborted) {
53+
throw new AbortError(undefined, { cause: signal.reason });
54+
}
55+
}
56+
57+
const lazy = lazyNet();
58+
// Strip the signal so listen() does not install its own close-on-abort
59+
// handler; rejecting and closing below tears the server down.
60+
const serverOptions = { ...options, signal: undefined };
61+
const server = lazy.createServer(serverOptions, connectionListener);
62+
63+
try {
64+
server.listen(serverOptions);
65+
await once(server, 'listening', signal !== undefined ? { signal } : kEmptyObject);
66+
} catch (err) {
67+
server.close();
68+
throw err;
69+
}
70+
return server;
71+
}
72+
73+
module.exports = {
74+
connect,
75+
listen,
76+
get isIP() { return lazyNet().isIP; },
77+
get isIPv4() { return lazyNet().isIPv4; },
78+
get isIPv6() { return lazyNet().isIPv6; },
79+
get BlockList() { return lazyNet().BlockList; },
80+
get SocketAddress() { return lazyNet().SocketAddress; },
81+
};

‎lib/net.js‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,7 @@ let cluster;
157157
let dns;
158158
let BlockList;
159159
let SocketAddress;
160+
let netPromises;
160161
let autoSelectFamilyDefault = getOptionValue('--network-family-autoselection');
161162
let autoSelectFamilyAttemptTimeoutDefault = getOptionValue('--network-family-autoselection-attempt-timeout');
162163

@@ -2853,6 +2854,10 @@ module.exports = {
28532854
connect,
28542855
createConnection: connect,
28552856
createServer,
2857+
get promises() {
2858+
netPromises ??= require('internal/net/promises');
2859+
return netPromises;
2860+
},
28562861
isIP: isIP,
28572862
isIPv4: isIPv4,
28582863
isIPv6: isIPv6,

‎lib/net/promises.js‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
'use strict';
2+
3+
module.exports = require('internal/net/promises');
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
'use strict';
2+
const common = require('../common');
3+
const assert = require('assert');
4+
const net = require('net');
5+
const { once } = require('events');
6+
const { connect } = require('net/promises');
7+
8+
(async () => {
9+
// Resolves with a connected socket and round-trips data.
10+
{
11+
const server = net.createServer((socket) => {
12+
socket.end('hello');
13+
}).listen(0);
14+
await once(server, 'listening');
15+
const socket = await connect({ port: server.address().port });
16+
assert.strictEqual(socket.connecting, false);
17+
const chunks = [];
18+
for await (const chunk of socket) {
19+
chunks.push(chunk);
20+
}
21+
assert.strictEqual(Buffer.concat(chunks).toString(), 'hello');
22+
server.close();
23+
}
24+
25+
// net.promises is the same object as require('net/promises').
26+
assert.strictEqual(net.promises, require('net/promises'));
27+
28+
// Rejects when the connection is refused.
29+
{
30+
const server = net.createServer().listen(0);
31+
await once(server, 'listening');
32+
const { port } = server.address();
33+
server.close();
34+
await once(server, 'close');
35+
await assert.rejects(connect({ port }), { code: 'ECONNREFUSED' });
36+
}
37+
38+
// A pre-aborted signal rejects with an AbortError.
39+
{
40+
await assert.rejects(
41+
connect({ port: 0, signal: AbortSignal.abort() }),
42+
{ name: 'AbortError' });
43+
}
44+
45+
// Aborting while connecting rejects with an AbortError.
46+
{
47+
const server = net.createServer().listen(0);
48+
await once(server, 'listening');
49+
const controller = new AbortController();
50+
const promise = connect({ port: server.address().port, signal: controller.signal });
51+
controller.abort();
52+
await assert.rejects(promise, { name: 'AbortError' });
53+
server.close();
54+
}
55+
56+
// An invalid signal throws.
57+
{
58+
await assert.rejects(
59+
connect({ port: 0, signal: 'INVALID_SIGNAL' }),
60+
{ code: 'ERR_INVALID_ARG_TYPE' });
61+
}
62+
})().then(common.mustCall());
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
'use strict';
2+
const common = require('../common');
3+
const assert = require('assert');
4+
const net = require('net');
5+
const { listen } = require('net/promises');
6+
7+
(async () => {
8+
// Resolves with a listening server.
9+
{
10+
const server = await listen({ port: 0 });
11+
assert.strictEqual(server.listening, true);
12+
assert.strictEqual(typeof server.address().port, 'number');
13+
server.close();
14+
}
15+
16+
// The connectionListener option receives incoming connections.
17+
{
18+
const server = await listen({
19+
port: 0,
20+
connectionListener: common.mustCall((socket) => {
21+
socket.end();
22+
server.close();
23+
}),
24+
});
25+
const client = net.connect(server.address().port);
26+
client.resume();
27+
}
28+
29+
// A pre-aborted signal rejects with an AbortError.
30+
{
31+
await assert.rejects(
32+
listen({ port: 0, signal: AbortSignal.abort() }),
33+
{ name: 'AbortError' });
34+
}
35+
36+
// Aborting while binding rejects with an AbortError and closes the server.
37+
{
38+
const controller = new AbortController();
39+
const promise = listen({ port: 0, signal: controller.signal });
40+
controller.abort();
41+
await assert.rejects(promise, { name: 'AbortError' });
42+
}
43+
44+
// An invalid signal throws.
45+
{
46+
await assert.rejects(
47+
listen({ port: 0, signal: 'INVALID_SIGNAL' }),
48+
{ code: 'ERR_INVALID_ARG_TYPE' });
49+
}
50+
51+
// Rejects when the address is already in use.
52+
{
53+
const first = await listen({ port: 0 });
54+
const { port } = first.address();
55+
await assert.rejects(listen({ port }), { code: 'EADDRINUSE' });
56+
first.close();
57+
}
58+
})().then(common.mustCall());

0 commit comments

Comments
 (0)