LogoPear Docs
ReferencesBareModules

bare-ws

WebSocket library for JavaScript

stable

bare-ws — WebSocket library for JavaScript.

npm i bare-ws

Usage

const ws = require('bare-ws')

const server = new ws.Server({ port: 8080 }, (socket) => {
  socket.on('data', (data) => {
    console.log(data.toString())
  })
})

server.on('listening', () => {
  const socket = new ws.Socket({ port: 8080 })

  socket.write('Hello WebSocket')
})

API

Socket

new Socket(opts: WebSocketOptions)

Open a WebSocket connection to url, or wrap an already-connected opts.socket when acting as the server side of a handshake.

Overloads:

new Socket(opts: WebSocketOptions)
new Socket(url: URL | string, opts?: WebSocketOptions)

Parameters

ParameterTypeDefaultDescription
optsWebSocketOptionsConnection options: host/hostname, port, path, secure, or an already-connected socket to wrap.

ping(data: unknown): void

Send a WebSocket ping frame with data as its payload.

Parameters

ParameterTypeDefaultDescription
dataunknownThe payload of the ping frame; a string is converted to a Buffer.

Throws

  • NOT_CONNECTED — the socket has not finished connecting.

pong(data: unknown): void

Send a WebSocket pong frame with data as its payload.

Parameters

ParameterTypeDefaultDescription
dataunknownThe payload of the pong frame; a string is converted to a Buffer.

Throws

  • NOT_CONNECTED — the socket has not finished connecting.

Socket.handshake(req: HTTPClientRequest, cb: (error: WebSocketError | null) => void): void

Perform the client side of the WebSocket opening handshake over req, calling cb with a WebSocketError if the server's response is invalid.

Parameters

ParameterTypeDefaultDescription
reqHTTPClientRequestThe outgoing HTTP request to upgrade; the WebSocket handshake headers are added to it.
cb(error: WebSocketError | null) => voidCalled once the server's response is validated, with a WebSocketError on failure, otherwise null.

Socket.WebSocketEvents

interface WebSocketEvents {
  ping: [payload: unknown]
  pong: [payload: unknown]
  data: [data: unknown]
  end: []
  readable: []
  piping: [dest: Writable]
  close: []
  error: [err: Error]
  drain: []
  finish: []
  pipe: [src: Readable]
}

Socket.WebSocketOptions

interface WebSocketOptions {
  host?: string
  hostname?: string
  path?: string
  port?: string | number
  secure?: boolean
  socket?: TCPSocket
}

Server

new Server(onconnection: (socket: WebSocket, req: HTTPClientRequest) => void)

Create a server, optionally backed by opts.server, and emit connection for each successful WebSocket upgrade.

Overloads:

new Server(onconnection: (socket: WebSocket, req: HTTPClientRequest) => void)
new Server(opts?: WebSocketServerOptions, onconnection?: (socket: WebSocket, req: HTTPClientRequest) => void)

Parameters

ParameterTypeDefaultDescription
onconnection(socket: WebSocket, req: HTTPClientRequest) => voidCalled on each 'connection' event.

address(): TCPSocketAddress

Return the bound address of the underlying TCP server.

close(cb?: (err?: Error | null) => void): this

Stop the server from accepting new connections, calling cb once it has closed.

Parameters

ParameterTypeDefaultDescription
cb?(err?: Error | null) => voidCalled once the underlying server has closed.

listening: boolean

true once the underlying server is bound and accepting connections.

ref(): this

Ref the underlying server so it keeps the event loop alive.

Server.handshake(req: HTTPClientRequest, cb: (err: WebSocketError | null) => void): void

Perform the server side of the WebSocket opening handshake for req, writing the 101 upgrade response on socket and calling cb with a WebSocketError on failure.

Overloads:

Server.handshake(req: HTTPClientRequest, cb: (err: WebSocketError | null) => void): void
Server.handshake(req: HTTPClientRequest, socket: TCPSocket, cb?: (err: WebSocketError | null) => void): void
Server.handshake(req: HTTPClientRequest, socket?: TCPSocket, head?: Buffer, cb?: (err: WebSocketError | null) => void): void

Parameters

ParameterTypeDefaultDescription
reqHTTPClientRequestThe incoming upgrade request.
cb(err: WebSocketError | null) => voidCalled with a WebSocketError if the request is not a valid WebSocket upgrade, otherwise null.

Server.WebSocketServerEvents

interface WebSocketServerEvents {
  connection: [socket: WebSocket, req: HTTPClientRequest]
  listening: []
  data: [data: unknown]
  end: []
  readable: []
  piping: [dest: Writable]
  close: []
  error: [err: Error]
  drain: []
  finish: []
  pipe: [src: Readable]
}

Server.WebSocketServerOptions

interface WebSocketServerOptions {
  secure?: boolean
  IncomingMessage?: typeof HTTPIncomingMessage
  ServerResponse?: typeof HTTPServerResponse
}

unref(): this

Unref the underlying server so it does not keep the event loop alive on its own.

bare-ws/global

Types

WebSocketConstructor

type WebSocketConstructor = typeof ws.Socket

The type of the Socket class, used to type the global WebSocket constructor.

bare-ws/constants

Constants and variables

EOL: string

The line ending (\r\n) used when writing the handshake response.

EOF: string

The blank-line terminator (\r\n\r\n) that ends the handshake response headers.

GUID: Buffer

The WebSocket protocol's fixed GUID, concatenated with the Sec-WebSocket-Key to compute the Sec-WebSocket-Accept digest.

opcode

opcode: {
  CONTINUATION: number
  TEXT: number
  BINARY: number
  CLOSE: number
  PING: number
  PONG: number
}

The WebSocket frame opcodes (CONTINUATION, TEXT, BINARY, CLOSE, PING, PONG) as defined by RFC 6455.

status: { PROTOCOL_ERROR: number; MESSAGE_TOO_LARGE: number }

WebSocket close status codes for protocol errors (PROTOCOL_ERROR) and oversized messages (MESSAGE_TOO_LARGE).

bare-ws/errors

WebSocketError

WebSocketError

new WebSocketError(msg: string, code: string, status: number, fn?: WebSocketError, cause?: unknown)

An error thrown for WebSocket protocol violations, carrying a code and a close status.

Parameters

ParameterTypeDefaultDescription
msgstringThe error message.
codestringThe error code.
statusnumberThe WebSocket close status associated with the error.
fn?WebSocketErrorOptional function to omit from the top of the generated stack trace, passed to Error.captureStackTrace.
cause?unknownThe underlying cause of the error, if any.

WebSocketError.EXPECTED_CONTINUATION(msg?: string): WebSocketError

A fragmented message's next frame was not a continuation frame.

Parameters

ParameterTypeDefaultDescription
msg?stringThe error message.

Returns WebSocketError — A WebSocketError with code set to 'EXPECTED_CONTINUATION', for the caller to throw.

WebSocketError.EXPECTED_MASK(msg?: string): WebSocketError

A frame from a client was missing its required mask.

Parameters

ParameterTypeDefaultDescription
msg?stringThe error message.

Returns WebSocketError — A WebSocketError with code set to 'EXPECTED_MASK', for the caller to throw.

WebSocketError.INCOMPLETE_FRAME(msg?: string, length?: number): WebSocketError

The buffered data does not yet contain a full frame.

Parameters

ParameterTypeDefaultDescription
msg?stringThe error message.
length?numberThe total byte length the frame needs before it can be decoded, stored as the error status (default -1).

Returns WebSocketError — A WebSocketError with code set to 'INCOMPLETE_FRAME' and status set to length, for the caller to throw.

WebSocketError.INVALID_ACCEPT_HEADER(msg?: string): WebSocketError

The Sec-WebSocket-Accept header in the server's handshake response did not match the expected digest.

Parameters

ParameterTypeDefaultDescription
msg?stringThe error message.

Returns WebSocketError — A WebSocketError with code set to 'INVALID_ACCEPT_HEADER', for the caller to throw.

WebSocketError.INVALID_ENCODING(msg?: string): WebSocketError

Data was written with an encoding other than buffer or utf8.

Parameters

ParameterTypeDefaultDescription
msg?stringThe error message.

Returns WebSocketError — A WebSocketError with code set to 'INVALID_ENCODING', for the caller to throw.

WebSocketError.INVALID_KEY_HEADER(msg?: string): WebSocketError

The Sec-WebSocket-Key header was missing or malformed.

Parameters

ParameterTypeDefaultDescription
msg?stringThe error message.

Returns WebSocketError — A WebSocketError with code set to 'INVALID_KEY_HEADER', for the caller to throw.

WebSocketError.INVALID_OPCODE(msg?: string): WebSocketError

A frame was received with an opcode that is not TEXT or BINARY.

Parameters

ParameterTypeDefaultDescription
msg?stringThe error message.

Returns WebSocketError — A WebSocketError with code set to 'INVALID_OPCODE', for the caller to throw.

WebSocketError.INVALID_PAYLOAD_LENGTH(msg?: string): WebSocketError

A frame's payload length field was invalid.

Parameters

ParameterTypeDefaultDescription
msg?stringThe error message.

Returns WebSocketError — A WebSocketError with code set to 'INVALID_PAYLOAD_LENGTH', for the caller to throw.

WebSocketError.INVALID_UPGRADE_HEADER(msg?: string): WebSocketError

The Upgrade header was missing or not websocket.

Parameters

ParameterTypeDefaultDescription
msg?stringThe error message.

Returns WebSocketError — A WebSocketError with code set to 'INVALID_UPGRADE_HEADER', for the caller to throw.

WebSocketError.INVALID_VERSION_HEADER(msg?: string): WebSocketError

The Sec-WebSocket-Version header was neither 8 nor 13.

Parameters

ParameterTypeDefaultDescription
msg?stringThe error message.

Returns WebSocketError — A WebSocketError with code set to 'INVALID_VERSION_HEADER', for the caller to throw.

WebSocketError.NETWORK_ERROR(msg: string, cause?: unknown): WebSocketError

The underlying HTTP request errored before the handshake completed.

Parameters

ParameterTypeDefaultDescription
msgstringThe error message.
cause?unknownThe underlying error.

Returns WebSocketError — A WebSocketError with code set to 'NETWORK_ERROR', for the caller to throw.

WebSocketError.NOT_CONNECTED(msg?: string): WebSocketError

An operation, such as ping() or pong(), was attempted before the socket finished connecting.

Parameters

ParameterTypeDefaultDescription
msg?stringThe error message.

Returns WebSocketError — A WebSocketError with code set to 'NOT_CONNECTED', for the caller to throw.

WebSocketError.UNEXPECTED_CONTINUATION(msg?: string): WebSocketError

A continuation frame was received without a preceding fragmented frame.

Parameters

ParameterTypeDefaultDescription
msg?stringThe error message.

Returns WebSocketError — A WebSocketError with code set to 'UNEXPECTED_CONTINUATION', for the caller to throw.

WebSocketError.UNEXPECTED_CONTROL(msg?: string): WebSocketError

A control frame was received while a fragmented message was in progress.

Parameters

ParameterTypeDefaultDescription
msg?stringThe error message.

Returns WebSocketError — A WebSocketError with code set to 'UNEXPECTED_CONTROL', for the caller to throw.

WebSocketError.UNEXPECTED_RSV1(msg?: string): WebSocketError

A frame was received with the reserved RSV1 bit set.

Parameters

ParameterTypeDefaultDescription
msg?stringThe error message.

Returns WebSocketError — A WebSocketError with code set to 'UNEXPECTED_RSV1', for the caller to throw.

WebSocketError.UNEXPECTED_RSV2(msg?: string): WebSocketError

A frame was received with the reserved RSV2 bit set.

Parameters

ParameterTypeDefaultDescription
msg?stringThe error message.

Returns WebSocketError — A WebSocketError with code set to 'UNEXPECTED_RSV2', for the caller to throw.

WebSocketError.UNEXPECTED_RSV3(msg?: string): WebSocketError

A frame was received with the reserved RSV3 bit set.

Parameters

ParameterTypeDefaultDescription
msg?stringThe error message.

Returns WebSocketError — A WebSocketError with code set to 'UNEXPECTED_RSV3', for the caller to throw.

See also

On this page

Usage
API
Socket
new Socket(opts: WebSocketOptions)
ping(data: unknown): void
pong(data: unknown): void
Socket.handshake(req: HTTPClientRequest, cb: (error: WebSocketError | null) => void): void
Socket.WebSocketEvents
Socket.WebSocketOptions
Server
new Server(onconnection: (socket: WebSocket, req: HTTPClientRequest) => void)
address(): TCPSocketAddress
close(cb?: (err?: Error | null) => void): this
listening: boolean
ref(): this
Server.handshake(req: HTTPClientRequest, cb: (err: WebSocketError | null) => void): void
Server.WebSocketServerEvents
Server.WebSocketServerOptions
unref(): this
bare-ws/global
Types
WebSocketConstructor
bare-ws/constants
Constants and variables
EOL: string
EOF: string
GUID: Buffer
opcode
status: { PROTOCOL_ERROR: number; MESSAGE_TOO_LARGE: number }
bare-ws/errors
WebSocketError
WebSocketError
WebSocketError.EXPECTED_CONTINUATION(msg?: string): WebSocketError
WebSocketError.EXPECTED_MASK(msg?: string): WebSocketError
WebSocketError.INCOMPLETE_FRAME(msg?: string, length?: number): WebSocketError
WebSocketError.INVALID_ACCEPT_HEADER(msg?: string): WebSocketError
WebSocketError.INVALID_ENCODING(msg?: string): WebSocketError
WebSocketError.INVALID_KEY_HEADER(msg?: string): WebSocketError
WebSocketError.INVALID_OPCODE(msg?: string): WebSocketError
WebSocketError.INVALID_PAYLOAD_LENGTH(msg?: string): WebSocketError
WebSocketError.INVALID_UPGRADE_HEADER(msg?: string): WebSocketError
WebSocketError.INVALID_VERSION_HEADER(msg?: string): WebSocketError
WebSocketError.NETWORK_ERROR(msg: string, cause?: unknown): WebSocketError
WebSocketError.NOT_CONNECTED(msg?: string): WebSocketError
WebSocketError.UNEXPECTED_CONTINUATION(msg?: string): WebSocketError
WebSocketError.UNEXPECTED_CONTROL(msg?: string): WebSocketError
WebSocketError.UNEXPECTED_RSV1(msg?: string): WebSocketError
WebSocketError.UNEXPECTED_RSV2(msg?: string): WebSocketError
WebSocketError.UNEXPECTED_RSV3(msg?: string): WebSocketError
See also