Workers - Support for Node.js DNS, Net, and Timer APIs in Workers
1y ago
Source
CloudflareWorkers - Support for Node.js DNS, Net, and Timer APIs in Workerscloudflare.comWhen using a Worker with the nodejs_compat compatibility flag enabled, you can now use the following Node.js APIs: node:net node:dns node:timers node:net You can use node:net to create a direct connection to servers via a TCP sockets with net.Socket . JavaScript import net from "node:net" ; const exampleIP = "127.0.0.1" ; export default { async fetch ( req ) { const socket = new net . Socket () ; socket . connect ( 4000 , exampleIP , function () { console . log ( "Connected" ) ; } ) ; socket . write ( "Hello, Server!" ) ; socket . end () ; return new Response ( "Wrote to server" , { status : 200 } ) ; }, }; TypeScript import net from "node:net" ; const exampleIP = "127.0.0.1" ; export default { async fetch ( req ) : Promise < Response > { const socket = new net . Socket () ; socket . connect ( 4000 , exampleIP , function () { console . log ( "Connected" ) ; } ) ; socket . write ( "Hello, Server!" ) ; socket . end () ; return new Response ( "Wrote to server" , { status : 200 } ) ; }, } satisfies ExportedHandler ; Additionally, you can now use other APIs including net.BlockList and net.SocketAddress . Note that net.Server is not supported. node:dns You can use node:dns for name resolution via DNS over HTTPS using Cloudflare DNS at 1.1.1.1. JavaScript import dns from "node:dns" ; let response = await dns . promises . resolve4 ( "cloudflare.com" , "NS" ) ; TypeScript import dns from 'node:dns' ; let response = await dns . promises . resolve4 ( 'cloudflare.com' , 'NS' ) ; All node:dns functions are available, except lookup , lookupService , and resolve which throw "Not implemented" errors when called. node:timers You can use node:timers to schedule functions to be called at some future period of time. This includes setTimeout for calling a function after a delay, setInterval for calling a function repeatedly, and setImmediate for calling a function in the next iteration of the event loop. JavaScript import timers from "node:timers" ; console . log ( "first" ) ; timers . setTimeout ( () => { console . log ( "last" ) ; }, 10 ) ; timers . setTimeout ( () => { console . log ( "next" ) ; } ) ; TypeScript import timers from "node:timers" ; console . log ( "first" ) ; timers . setTimeout ( () => { console . log ( "last" ) ; }, 10 ) ; timers . setTimeout ( () => { console . log ( "next" ) ; } )
You might also wanna read
Bun v0.7.0
bun.com·2y ago
Bun v1.0.32
bun.com·2y ago
OpenWorkers: Open-Source Runtime for Self-Hosted Cloudflare Workers Implementation
OpenWorkers is an open-source runtime that enables developers to run Cloudflare Workers-style JavaScript applications on their own infrastru
Bun v1.2.12
bun.com·1y ago
Bun v0.6.3
bun.com·3y ago
Bun v0.8.1
bun.com·2y ago

Comments
Sign in to join the conversation.
No comments yet. Be the first.