npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@betaweb/websockets

v1.2.3

Published

A simple JavaScript class to handle browser-side Websockets

Downloads

29

Readme

Websockets

A simple JavaScript class to handle browser-side Websockets.

Note : this library provides an API only for browser-side Websokets.

Getting started

Include Websockets.min.js script in your HTML :

<script defer src="path/to/Websockets.min.js"></script>

And declare a new instance in your script :

const client = new Websockets({
    port: 9000,
    scheme: 'ws',
    onprogress(progress, dataSize, data) {
        if (progress === 0) {
            console.log('Data sended successfully !')
        } else {
            console.log(`${dataSize - progress}/${dataSize} bytes have been sent.`)
        }
    }
})

client.on(Websockets.DEFAULT_EVENTS.CONNECTED, () => {
    console.log("It's alive ! ALIVE !")
})

client.on('wakedup', () => {
    console.log("Waked up !")
})

await client.connect()

await client.emit('wakeup', { body: "It's time to wake up !" })

client.destroy()

And.. that's it ! :)

Available getters and methods

Getters

// Websockets class default options
static DEFAULT_OPTIONS: Object.<String, any>

// WebSocket native API close codes by status
static CLOSE_STATUS: Object.<String, Number>

// WebSocket  native API close messages by codes
static CLOSE_STATUS_MESSAGES: Object.<Number, String>

// Websockets class default events
static DEFAULT_EVENTS: Object.<String, String>

// returns true if WebSocket API is supported by the actual browser, false otherwise
static hasSupport: Boolean

// WebSocket schme ('auto', 'ws', 'wss')
scheme: String

// WebSocket URL
url: String

// Registered events via `Websockets.on()` method
events: Object.<String, Array>

// returns true if WebSocket client is instantiated, false otherwise
isInitialized: Boolean

// returns true if WebSocket client is connecting, false otherwise
isConnecting: Boolean

// returns true if WebSocket client is connected, false otherwise
isOpen: Boolean

// returns true if WebSocket client is sending data, false otherwise
isSending: Boolean

// returns true if WebSocket connection is closing or closed, false otherwise
isClosed: Boolean

Methods

connect(): Promise

Connect the WebSocket client to the specified endpoint.

Example :

await client.connect()

send(data: any): Promise

send data to the server.

Example :

await client.send('PING')

emit(type: String, payload?: any = '', namespaced?: boolean = true): Promise

Format a data object with type and payload, and send it to the server. If namespaced is false, type parameter will doesn't be prefixed by the namespace specified in the Websockets instance options.

Example :

// Emit 'USER_MESSAGE' event to the server with a payload
await client.emit('USER_MESSAGE', { message: 'Hello, World !', user_id: 1 })


// Emit 'USER_MESSAGE' event to the server with a payload and without namespace
await client.emit('USER_MESSAGE', { message: 'Hello, World !', user_id: 1 }, false)

on(type: String, callback: Function, namespaced?: boolean = true): Websockets

Add an event. If namespaced is false, type parameter will doesn't be prefixed by the namespace specified in the Websockets instance options.

Example :

// Listen to 'PONG' event from the server
client.on('PONG', () => console.log('The server responds with PONG !'))

// Send 'PING' event to the server
await client.send('PING')

once(type: String, callback: Function, namespaced?: boolean = true): Websockets

Add an event. This event will be listenend only once. After that, it will be deleted. If namespaced is false, type parameter will doesn't be prefixed by the namespace specified in the Websockets instance options.

Example :

// Listen to 'PONG' event from the server
client.once('PONG', () => console.log('This event is unique !'))

// Send 'PING' event to the server
await client.send('PING')

off(type: String, callback?: Function = null, namespaced?: boolean = true): Websockets

Removes an event. if callback parameter is null, all events of type type will be removed, otherwise, only the event that corresponds to the callback parameter will be removed. If namespaced is false, type parameter doesn't be prefixed by the namespace specified in the Websockets instance options.

Example :

const onPong = () => console.log("The server responds with PONG !\n")

// Listen to 'PONG' event from the server
client.on('PONG', onPong)

// Send 'PING' event to the server
await client.send('PING')

// Detach 'PONG' event listener
client.off('PONG', onPong)

onMessage(callback: Function): Websockets

The callback parameter will be triggered with each message sent from the server.

Example :

client.onMessage(data => console.log(data))

disconnect(): void

disconnect the WebSocket client.

Example :

client.disconnect()

destroy(): void

Remove all Websockets events and disconnect the WebSocket client.

Example :

client.destroy()

Instance options

TODO