ws
The ws module provides a WebSocket client for JSH applications.
It exposes a single WebSocket class built on top of the native Go WebSocket client.
Typical usage looks like this.
const { WebSocket } = require('ws');WebSocket
Creates a WebSocket client connection.
Syntax
new WebSocket(url)Parameters
urlString: WebSocket server address such asws://host:port/pathorwss://host:port/path.
If url is missing or is not a string, the constructor throws TypeError.
Properties
| Property | Type | Description |
|---|---|---|
url | String | Original WebSocket URL passed to the constructor. |
readyState | Number | Current connection state. |
readyState values
WebSocket.CONNECTING=0WebSocket.OPEN=1WebSocket.CLOSING=2WebSocket.CLOSED=3
Message type constants
WebSocket.TextMessage=1WebSocket.BinaryMessage=2
send()
Sends a message to the server.
Syntax
ws.send(data)Parameters
dataString: Message text to send.
If the socket is not open, the module emits an error event.
Usage example
| |
close()
Closes the current connection.
Syntax
ws.close()Calling close() transitions the socket through CLOSING to CLOSED and emits close.
Events
WebSocket extends EventEmitter and supports normal event-listener patterns such as on() and addListener().
open
Emitted after the client successfully connects.
ws.on('open', () => {
console.println('connected');
});close
Emitted when the connection closes.
ws.on('close', () => {
console.println('closed');
});message
Emitted when a message arrives from the server.
The callback receives an event-like object with these fields.
| Field | Type | Description |
|---|---|---|
type | Number | Message type such as WebSocket.TextMessage or WebSocket.BinaryMessage. |
data | String or byte data | Message payload. Text messages are exposed as strings. |
| |
error
Emitted when connection or send operations fail.
ws.on('error', (err) => {
console.println(err.message);
});Usage example
| |
Behavior notes
- The module implements a WebSocket client only. It does not provide server-side upgrade handling.
- Connection establishment is started asynchronously from the constructor.
- Connection failures are reported through the
errorevent. - Incoming messages may be text or binary, but the JavaScript
send()method is intended for text message usage.