Connect with Node’s built-in WebSocket client
Open a WebSocket from Node, send a text message after the connection opens, and close the client after the reply.
Your Node script needs to ask a running WebSocket server one question and print the reply. Use Node’s built-in client to send one message, print the reply and close the connection.
Node 22 enabled the global WebSocket by default and marked it stable in 22.4.0. The client follows the browser API, including addEventListener and MessageEvent.data. If you are moving from ws, change the event code as well as taking out the import.
Send once the connection opens
Use an existing endpoint that replies with the text pong when it receives ping. Save this as ping.mjs and pass the endpoint URL as the first argument when running it with Node.
const url = process.argv[2]
if (!url) throw new Error("Pass a WebSocket URL")
const socket = new WebSocket(url)
let received = false
const deadline = setTimeout(() => {
console.error("Timed out waiting for a reply")
process.exitCode = 1
socket.close()
}, 3000)
socket.addEventListener("open", () => socket.send("ping"), { once: true })
socket.addEventListener("message", ({ data }) => {
received = true
console.log(data)
socket.close(1000)
}, { once: true })
socket.addEventListener("error", () => {
clearTimeout(deadline)
console.error("WebSocket error")
process.exitCode = 1
}, { once: true })
socket.addEventListener("close", ({ code }) => {
clearTimeout(deadline)
if (!received || code !== 1000) process.exitCode = 1
}, { once: true })Against the text endpoint, you see pong on stdout and the client closes with code 1000.
The constructor starts connecting. The open handler tells you when it is safe to send. Calling send while the client is still connecting throws, so move any initial message into that handler during the migration.
Keep a failed connection visible to the caller
Try the script with an endpoint that refuses the connection. It reports an error and returns a failing exit status. The deadline also covers a server that accepts the connection and sends no reply. It limits how long the script waits before initiating close, which can take additional time.
Check the constructor options in your old client before removing the dependency. The standard constructor takes a URL and optional subprotocols. If the old call uses custom handshake headers or agent options, check for another supported client before removing ws.