Get started

Here is a quick walkthrough on how to put the library to use in your project.


Sarus can be installed using npm:

npm i @anephenix/sarus

Usage and attaching event listeners

Once you have installed the library, you can include it in your project's code like this:

// import the module 
import Sarus from '@anephenix/sarus';

  If you know what event listener functions you want
  to bind to the WebSocket connection, you can pass
  them directly to Sarus at the time of creating the

// Log a message that the connection is open
const noteOpened = () => console.log('Connection opened');

// Assuming that the WebSocket server is sending JSON data,
// you can use this to parse the data payload;
const parseMessage = event => {
  const message = JSON.parse(;
  // Then do what you like with the message

// Log a message that the connection has closed
const noteClosed = () => console.log('Connection closed');

// If an error occurs, throw the error
const throwError = error => throw error;

// Create an instance of Sarus with the event listeners
const sarus = new Sarus({
  url: 'wss://',
  eventListeners: {
    open: [noteOpened],
    message: [parseMessage],
    close: [notedClosed],
    error: [throwError]

You can also attach event listeners to the instance of Sarus after creating it, giving you lots of flexibility in how you interact with events on the WebSocket:

// Logs messages to the console for debugging
const logMessage = (event) => {

// Attach the event listener
sarus.on('message', logMessage);

You can also unattach event listeners from the Sarus instance:

  Remove a function from the Sarus 
  event listener by function variable
*/'message', logMessage);

  You can also remove the event Listener 
  by the name of the function
*/'message', 'parseMessage');

Sending messages

Sending messages in Sarus is identical to how you would send messages with a WebSocket:

sarus.send('Hello world');

Closing the connection

If you want to close the WebSocket connection (for example when the user logs off from an app), then you can do that by calling this:


That will close the WebSocket connection from the client, and Sarus will not attempt to re-establish the connection, as the WebSocket connection closure is intentional.

That covers a basic use case of Sarus to handle WebSockets. There are some more advanced features of Sarus, which are worth exploring in the documentation, as well as seeing in action on the demos page.