From 0ef6678a079dfe74c42fb4747dbb2adb29ce0208 Mon Sep 17 00:00:00 2001 From: Sam Clegg Date: Tue, 14 Apr 2026 11:04:33 -0700 Subject: [PATCH] Allow use of builtin node WebSocket when available. NFS Node v21 and up have native WebSocket support. This change makes the import of the external `ws` module conditional so it will only run on older versions of node. See #26676 --- src/lib/libsockfs.js | 22 +++++++++---------- .../test_codesize_hello_dylink_all.json | 4 ++-- 2 files changed, 12 insertions(+), 14 deletions(-) diff --git a/src/lib/libsockfs.js b/src/lib/libsockfs.js index a9e99be7729ee..a4e0497e1815e 100644 --- a/src/lib/libsockfs.js +++ b/src/lib/libsockfs.js @@ -212,17 +212,13 @@ addToLibrary({ #if SOCKET_DEBUG dbg(`websocket: connect: ${url}, ${subProtocols.toString()}`); #endif +#if MIN_NODE_VERSION < 220400 // If node we use the ws library. - var WebSocketConstructor; -#if ENVIRONMENT_MAY_BE_NODE - if (ENVIRONMENT_IS_NODE) { - WebSocketConstructor = /** @type{(typeof WebSocket)} */(require('ws')); - } else -#endif // ENVIRONMENT_MAY_BE_NODE - { - WebSocketConstructor = WebSocket; + if (ENVIRONMENT_IS_NODE && !globalThis.WebSocket) { + globalThis.WebSocket = /** @type{(typeof WebSocket)} */(require('ws')); } - ws = new WebSocketConstructor(url, opts); +#endif // MIN_NODE_VERSION < 220400 + ws = new WebSocket(url, opts); ws.binaryType = 'arraybuffer'; } catch (e) { #if SOCKET_DEBUG @@ -338,8 +334,8 @@ addToLibrary({ SOCKFS.emit('message', sock.stream.fd); } -#if ENVIRONMENT_MAY_BE_NODE - if (ENVIRONMENT_IS_NODE) { +#if MIN_NODE_VERSION < 220400 + if (ENVIRONMENT_IS_NODE && peer.socket.on) { // EventEmitter-style events use by ws library objects in Node.js). peer.socket.on('open', handleOpen); peer.socket.on('message', (data, isBinary) => { @@ -511,10 +507,12 @@ addToLibrary({ sock.connecting = true; }, listen(sock, backlog) { +#if !ENVIRONMENT_MAY_BE_NODE + throw new FS.ErrnoError({{{ cDefs.EOPNOTSUPP }}}); +#else if (!ENVIRONMENT_IS_NODE) { throw new FS.ErrnoError({{{ cDefs.EOPNOTSUPP }}}); } -#if ENVIRONMENT_MAY_BE_NODE if (sock.server) { throw new FS.ErrnoError({{{ cDefs.EINVAL }}}); // already listening } diff --git a/test/codesize/test_codesize_hello_dylink_all.json b/test/codesize/test_codesize_hello_dylink_all.json index de173f10013aa..617823e781baa 100644 --- a/test/codesize/test_codesize_hello_dylink_all.json +++ b/test/codesize/test_codesize_hello_dylink_all.json @@ -1,7 +1,7 @@ { - "a.out.js": 244238, + "a.out.js": 244296, "a.out.nodebug.wasm": 577664, - "total": 821902, + "total": 821960, "sent": [ "IMG_Init", "IMG_Load",