ws-emitter
v1.0.1
Published
**`@packages/ws-emitter`** is a lightweight wrapper around native WebSocket that adds event subscription and automatic reconnection functionality out-of-the-box. It also supports MessagePack decoding (via [`msgpackr`](https://github.com/kriszyp/msgpackr))
Downloads
11
Readme
@packages/ws-emitter
@packages/ws-emitter is a lightweight wrapper around native WebSocket that adds event subscription and automatic reconnection functionality out-of-the-box.
It also supports MessagePack decoding (via msgpackr) if needed.
✨ Features
- Simple event-based API
- Auto-reconnect support with customizable delay
- Optional MessagePack decoding
- Manual and automatic connection management
- Lightweight, no external dependencies (except for optional
msgpackr)
Installation
npm install @packages/ws-emitteror
yarn add @packages/ws-emitterQuick Start
import { WsEmitter } from '@packages/ws-emitter';
const notifier = new WsEmitter('wss://foo.bar');
notifier.on('open', (event) => console.log('WebSocket open', event));
notifier.on('close', (event) => console.log('WebSocket closed', event));
notifier.on('message', (data) => console.log('Received message', data));
notifier.on('error', (event) => console.error('WebSocket error', event));
// Emit a local event
notifier.emit('custom-event', { foo: 'bar' });API
new WsEmitter(url: string, options?: OptionsType, isMessagePack?: boolean)
Create a new WebSocket connection with event subscription and optional automatic reconnection.
| Parameter | Type | Default | Description |
| --------------- | ------------- | -------------------------------------------------------------------- | ------------------------------------ |
| url | string | required | WebSocket server URL |
| options | OptionsType | { autoConnect: true, autoReconnect: true, reconnectTimeout: 1000 } | Connection options |
| isMessagePack | boolean | false | Enable decoding MessagePack messages |
Example
const notifier = new WsEmitter('wss://foo.bar');
const notifier = new WsEmitter('wss://foo.bar', { autoConnect: false, autoReconnect: true });
notifier.connect();
const notifier = new WsEmitter('wss://foo.bar', { autoConnect: false, autoReconnect: false });
notifier.connect();instance.connect()
Manually initiate a WebSocket connection.
const notifier = new WsEmitter('wss://foo.bar', { autoConnect: false });
notifier.connect();instance.close(force?: boolean)
Closes the WebSocket connection.
If force is true, auto-reconnection will be disabled temporarily for this closure.
| Parameter | Type | Default | Description |
| --------- | --------- | ------- | ------------------------------------ |
| force | boolean | false | Prevent auto-reconnect after closing |
Example
notifier.close();
notifier.close(true);instance.on(eventName: string, callback: (payload: any) => void)
Subscribe to WebSocket or custom events.
Built-in WebSocket events:
opencloseerrormessage
Example
notifier.on('message', (data) => {
console.log('Received data:', data);
});
notifier.on('open', () => {
console.log('Connection established!');
});instance.emit(eventName: string, payload: any)
Trigger a local event manually (client-side only).
Example
notifier.emit('custom-event', { hello: 'world' });
notifier.on('custom-event', (data) => {
console.log('Custom event received:', data);
});Note:
emitdoes not send data to the server, it triggers client-side handlers only.
Options
You can configure behavior with the following options:
interface OptionsType {
autoConnect?: boolean;
autoReconnect?: boolean;
reconnectTimeout?: number;
}| Option | Type | Default | Description |
| ------------------ | --------- | ------- | --------------------------------------------- |
| autoConnect | boolean | true | Automatically connect after instance creation |
| autoReconnect | boolean | true | Automatically reconnect after disconnection |
| reconnectTimeout | number | 1000 | Delay (ms) before attempting reconnect |
MessagePack Support
To enable MessagePack decoding for binary WebSocket messages, pass true as the third argument:
const notifier = new WsEmitter('wss://foo.bar', undefined, true);MessagePack messages will be automatically unpacked using msgpackr.
Events
| Event name | Payload Type | Description |
| ---------- | ---------------- | ------------------------------ |
| open | WebSocketEvent | Connection successfully opened |
| close | WebSocketEvent | Connection closed |
| error | WebSocketEvent | Connection error |
| message | any | Received message |
Example: Reconnect on Close
const notifier = new WsEmitter('wss://foo.bar');
notifier.on('close', () => {
console.log('Connection closed, trying to reconnect...');
});📜 License
Distributed under the MIT License. See LICENSE for more information.
📧 Contact
For support or questions, contact us at @arsenicum32
🙏 Credits
Developed by ARS33 Inspired by modern localization needs Built with ❤️ for the open source community
