Skip to content

Commit 911aef9

Browse files
authored
Adding changelog for node compat improvements (#19341)
Adding changelog for node compat improvements and node API docs
1 parent 251b2bc commit 911aef9

File tree

6 files changed

+223
-21
lines changed

6 files changed

+223
-21
lines changed
Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
---
2+
title: Support for Node.js DNS, Net, and Timer APIs in Workers
3+
description: Node.js APIs from the node:dns, node:net, and node:timers modules are now available when using nodejs_compat.
4+
products:
5+
- workers
6+
date: 2025-01-28T13:00:00Z
7+
---
8+
9+
import { Render, PackageManagers, TypeScriptExample } from "~/components";
10+
11+
When using a Worker with the [`nodejs_compat`](/workers/runtime-apis/nodejs/) compatibility flag enabled, you can now use the following Node.js APIs:
12+
13+
- [`node:net`](/workers/runtime-apis/nodejs/net/)
14+
- [`node:dns`](/workers/runtime-apis/nodejs/dns/)
15+
- [`node:timers`](/workers/runtime-apis/nodejs/timers/)
16+
17+
#### node:net
18+
19+
This makes it possible to connect to databases such as [MySQL](https://www.mysql.com/), [PostgreSQL](https://www.postgresql.org/),
20+
[Redis](https://redis.io/), or [MongoDB](https://github.com/mongodb/mongo). Though for production use, we recommend that you connect
21+
using TLS, which can be done with the [`cloudflare:sockets`](/workers/runtime-apis/tcp-sockets/#connect)
22+
module, or prefereably by using [Hyperdrive](/hyperdrive), which includes
23+
[connection pooling](/hyperdrive/configuration/how-hyperdrive-works/#connection-pooling)
24+
and [query caching](/hyperdrive/configuration/how-hyperdrive-works/#query-caching).
25+
26+
<TypeScriptExample filename="index.ts">
27+
```ts
28+
import net from "node:net";
29+
30+
const exampleIP = "127.0.0.1";
31+
32+
export default {
33+
async fetch(req): Promise<Response> {
34+
const socket = new net.Socket();
35+
socket.connect(4000, exampleIP, function () {
36+
console.log("Connected");
37+
});
38+
39+
socket.write("Hello, Server!");
40+
socket.end();
41+
42+
return new Response("Wrote to server", { status: 200 });
43+
},
44+
} satisfies ExportedHandler;
45+
````
46+
</TypeScriptExample>
47+
48+
Additionally, you can now use other APIs incliding [`net.BlockList`](https://nodejs.org/api/net.html#class-netblocklist) and
49+
[`net.SocketAddress`](https://nodejs.org/api/net.html#class-netsocketaddress).
50+
51+
Note that [`net.Server`](https://nodejs.org/api/net.html#class-netserver) is not supported.
52+
53+
#### node:dns
54+
55+
You can use [`node:dns`](https://nodejs.org/api/dns.html) for name resolution via [DNS over HTTPS](/1.1.1.1/encryption/dns-over-https/) using
56+
[Cloudflare DNS](https://www.cloudflare.com/application-services/products/dns/) at 1.1.1.1.
57+
58+
<TypeScriptExample filename="index.ts">
59+
```ts
60+
import dns from "node:dns";
61+
62+
dns.lookup("example.org", (_err: any, address: string, ipFamily: number) =>
63+
console.log(`address: ${address} family: IPv${ipFamily}`));
64+
````
65+
66+
</TypeScriptExample>
67+
68+
All `node:dns` functions are available, except `lookup`, `lookupService`, and `resolve` which throw "Not implemented" errors when called.
69+
70+
#### node:timers
71+
72+
You can use [`node:timers`](https://nodejs.org/api/timers.html) to schedule functions to be called at some future period of time.
73+
74+
This includes [`setTimeout`](https://nodejs.org/api/timers.html#settimeoutcallback-delay-args) for calling a function after a delay,
75+
[`setInterval`](https://nodejs.org/api/timers.html#setintervalcallback-delay-args) for calling a function repeatedly,
76+
and [`setImmediate`](https://nodejs.org/api/timers.html#setimmediatecallback-args) for calling a function in the next iteration of the event loop.
77+
78+
<TypeScriptExample filename="index.ts">
79+
```ts
80+
import timers from "node:timers";
81+
82+
console.log("first");
83+
timers.setTimeout(() => {
84+
console.log("last");
85+
}, 10);
86+
87+
timers.setTimeout(() => {
88+
console.log("next");
89+
});
90+
```
91+
</TypeScriptExample>
Lines changed: 8 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,39 +1,35 @@
11
---
22
pcx_content_type: configuration
33
title: assert
4-
54
---
65

7-
import { Render } from "~/components"
6+
import { Render } from "~/components";
87

98
<Render file="nodejs-compat-howto" />
109

1110
The `assert` module in Node.js provides a number of useful assertions that are useful when building tests.
1211

1312
```js
14-
import {
15-
strictEqual,
16-
deepStrictEqual,
17-
ok,
18-
doesNotReject,
19-
} from 'node:assert';
13+
import { strictEqual, deepStrictEqual, ok, doesNotReject } from "node:assert";
2014

2115
strictEqual(1, 1); // ok!
2216
strictEqual(1, "1"); // fails! throws AssertionError
2317

24-
deepStrictEqual({ a: { b: 1 }}, { a: { b: 1 }});// ok!
25-
deepStrictEqual({ a: { b: 1 }}, { a: { b: 2 }});// fails! throws AssertionError
18+
deepStrictEqual({ a: { b: 1 } }, { a: { b: 1 } }); // ok!
19+
deepStrictEqual({ a: { b: 1 } }, { a: { b: 2 } }); // fails! throws AssertionError
2620

2721
ok(true); // ok!
2822
ok(false); // fails! throws AssertionError
2923

3024
await doesNotReject(async () => {}); // ok!
31-
await doesNotReject(async () => { throw new Error('boom') }); // fails! throws AssertionError
25+
await doesNotReject(async () => {
26+
throw new Error("boom");
27+
}); // fails! throws AssertionError
3228
```
3329

3430
:::note
3531

36-
In the Workers implementation of `assert`, all assertions run in, what Node.js calls, the strict assertion mode. In strict assertion mode, non-strict methods behave like their corresponding strict methods. For example, `deepEqual()` will behave like `deepStrictEqual()`.
32+
In the Workers implementation of `assert`, all assertions run in, what Node.js calls, the strict assertion mode. In strict assertion mode, non-strict methods behave like their corresponding strict methods. For example, `deepEqual()` will behave like `deepStrictEqual()`.
3733
:::
3834

3935
Refer to the [Node.js documentation for `assert`](https://nodejs.org/dist/latest-v19.x/docs/api/assert.html) for more information.
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
---
2+
pcx_content_type: configuration
3+
title: dns
4+
---
5+
6+
import { Render, TypeScriptExample } from "~/components";
7+
8+
<Render file="nodejs-compat-howto" />
9+
10+
You can use [`node:dns`](https://nodejs.org/api/dns.html) for name resolution via [DNS over HTTPS](/1.1.1.1/encryption/dns-over-https/) using
11+
[Cloudflare DNS](https://www.cloudflare.com/application-services/products/dns/) at 1.1.1.1.
12+
13+
<TypeScriptExample filename="index.ts">
14+
```ts
15+
import dns from "node:dns";
16+
17+
dns.lookup("example.org", (_err: any, address: string, ipFamily: number) =>
18+
console.log(`address: ${address} family: IPv${ipFamily}`));
19+
```
20+
</TypeScriptExample>
21+
22+
:::note
23+
24+
DNS requests will execute a subrequest, counts for your [Worker's subrequest limit](/workers/platform/limits/#subrequests).
25+
26+
:::
27+
28+
The full `node:dns` API is documented in the [Node.js documentation for `node:dns`](https://nodejs.org/api/dns.html).
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
---
2+
pcx_content_type: configuration
3+
title: net
4+
---
5+
6+
import { Render, TypeScriptExample } from "~/components";
7+
8+
<Render file="nodejs-compat-howto" />
9+
10+
You can use [`node:net`](https://nodejs.org/api/net.html) to create a direct connection to servers via a TCP sockets
11+
with [`net.Socket`](https://nodejs.org/api/net.html#class-netsocket).
12+
13+
This makes it possible to connect to databases such as [MySQL](https://www.mysql.com/), [PostgreSQL](https://www.postgresql.org/),
14+
[Redis](https://redis.io/), or [MongoDB](https://github.com/mongodb/mongo). Though for production use, we recommend that you connect
15+
using TLS, which can be done with the [`cloudflare:sockets`](/workers/runtime-apis/tcp-sockets/#connect)
16+
module, or prefereably by using [Hyperdrive](/hyperdrive), which includes
17+
[connection pooling](/hyperdrive/configuration/how-hyperdrive-works/#connection-pooling)
18+
and [query caching](/hyperdrive/configuration/how-hyperdrive-works/#query-caching).
19+
20+
These functions use [`connect`](/workers/runtime-apis/tcp-sockets/#connect) functionality from the built-in `cloudflare:sockets` module.
21+
22+
<TypeScriptExample filename="index.ts">
23+
```ts
24+
import net from "node:net";
25+
26+
const exampleIP = "127.0.0.1";
27+
28+
export default {
29+
async fetch(req): Promise<Response> {
30+
const socket = new net.Socket();
31+
socket.connect(4000, exampleIP, function () {
32+
console.log("Connected");
33+
});
34+
35+
socket.write("Hello, Server!");
36+
socket.end();
37+
38+
return new Response("Wrote to server", { status: 200 });
39+
},
40+
} satisfies ExportedHandler;
41+
42+
```
43+
</TypeScriptExample>
44+
45+
Additionally, other APIs such as [`net.BlockList`](https://nodejs.org/api/net.html#class-netblocklist)
46+
and [`net.SocketAddress`](https://nodejs.org/api/net.html#class-netsocketaddress) are available.
47+
48+
Note that the [`net.Server`](https://nodejs.org/api/net.html#class-netserver) class is not supported by Workers.
49+
50+
The full `node:net` API is documented in the [Node.js documentation for `node:net`](https://nodejs.org/api/net.html).
Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,18 @@
11
---
22
pcx_content_type: configuration
33
title: path
4-
54
---
65

7-
import { Render } from "~/components"
6+
import { Render } from "~/components";
87

98
<Render file="nodejs-compat-howto" />
109

1110
The [`node:path`](https://nodejs.org/api/path.html) module provides utilities for working with file and directory paths. The `node:path` module can be accessed using:
1211

1312
```js
14-
import path from "node:path"
15-
path.join('/foo', 'bar', 'baz/asdf', 'quux', '..');
13+
import path from "node:path";
14+
path.join("/foo", "bar", "baz/asdf", "quux", "..");
1615
// Returns: '/foo/bar/baz/asdf'
1716
```
1817

19-
:::note
20-
21-
In the Workers implementation of `path`, the [path.win32](https://nodejs.org/api/path.html#windows-vs-posix) variants of the path API are not implemented, and will throw an exception.
22-
:::
23-
2418
Refer to the [Node.js documentation for `path`](https://nodejs.org/api/path.html) for more information.
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
---
2+
pcx_content_type: configuration
3+
title: timers
4+
---
5+
6+
import { Render, TypeScriptExample } from "~/components";
7+
8+
<Render file="nodejs-compat-howto" />
9+
10+
Use [`node:timers`](https://nodejs.org/api/timers.html) APIs to schedule functions to be executed later.
11+
12+
This includes [`setTimeout`](https://nodejs.org/api/timers.html#settimeoutcallback-delay-args) for calling a function after a delay,
13+
[`setInterval`](https://nodejs.org/api/timers.html#clearintervaltimeout) for calling a function repeatedly,
14+
and [`setImmediate`](https://nodejs.org/api/timers.html#setimmediatecallback-args) for calling a function in the next iteration of the event loop.
15+
16+
<TypeScriptExample filename="index.ts">
17+
```ts
18+
import timers from "node:timers";
19+
20+
console.log("first");
21+
timers.setTimeout(() => {
22+
console.log("last");
23+
}, 10);
24+
25+
timers.setTimeout(() => {
26+
console.log("next");
27+
});
28+
```
29+
</TypeScriptExample>
30+
31+
:::note
32+
Due to [security-based restrictions on timers](/workers/reference/security-model/#step-1-disallow-timers-and-multi-threading) in Workers,
33+
timers are limited to returning the time of the last I/O. This means that while setTimeout, setInterval, and setImmediate will defer your function execution
34+
until after other events have run, they will not delay them for the full time specified.
35+
:::
36+
37+
:::note
38+
When called from a global level (on [`globalThis`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis)),
39+
functions such as `clearTimeout` and `setTimeout` will respect web standards rather than Node.js-specific functionality. For complete Node.js
40+
compatibility, you must call functions from the `node:timers` module.
41+
:::
42+
43+
The full `node:timers` API is documented in the [Node.js documentation for `node:timers`](https://nodejs.org/api/timers.html).

0 commit comments

Comments
 (0)