Get started
This is a quick guide to getting Sarus installed and running in your application.
Installation
You can install Sarus via npm:
npm i @anephenix/sarus
Once you have it installed, you can load it like this:
// import the module
import Sarus from '@anephenix/sarus';
// Initialize an instance of Sarus
const sarus = new Sarus({
// The URL of the WebSocket server
url: 'wss://ws.anephenix.com'
});
Next, we'll show you how to attach event listeners to the WebSocket.
Adding WebSocket event listeners
There are 2 ways that you can attach the WebSocket event listeners in Sarus:
- At the time of instantiating the
Sarus
class instance. - By calling the
.on
method on theSarus
instance after it has been created.
Via instantiating the Sarus
class instance
When you instantiate the Sarus
class, you can setup the event listeners 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
connection:
*/
// 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(event.data);
// 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://ws.anephenix.com',
eventListeners: {
open: [noteOpened],
message: [parseMessage],
close: [notedClosed],
error: [throwError]
}
});
You can attach event listeners for the following events:
- open
- message
- error
- close
Via the .on
method
Alternatively, you can attach the event listeners after the Sarus
instance has been created by calling the .on
method on the instance:
// Logs messages to the console for debugging
const logMessage = (event) => {
console.log(event.data);
};
// Attach the event listener
sarus.on('message', logMessage);
This works for the following events:
- open
- message
- error
- close
Sending messages
You can send a message like this:
sarus.send('Hello world');
If you want to send other types of payloads like JSON objects, encode the data as a string before sending it:
const payload = {
type: 'action',
content: 'get-weather',
location: 'London, UK'
};
const encodedPayload = JSON.stringify(payload);
sarus.send(encodedPayload);
If you are sending binary data instead, it is possible to send that as well, which we will cover in the documentation.
Next steps
This is a quick and simple guide to getting started with Sarus, but there are more features to the library that you might want to explore. Check out the documentation for more.