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

pubsub-ws

v2.0.1-beta.4

Published

pubsub-ws is a simple Node JS library for communicating over websockets using the publish-subscribe pattern.

Downloads

473

Readme

pubsub-ws

pubsub-ws is a simple Node JS library for communicating over websockets using the publish-subscribe pattern.

It is written in Typescript and uses the ws package for websockets. The author's primary use case was to push real time updates to a web UI for features such as graphs and progress bars. However, it could be used anywhere that pubsub over websockets is needed.

Terminology

  • channel - A channel is a filter of published messages that clients can subscribe to. For example, I am interested in cats, so I subscribe to the "cats" channel and start receiving all messages published to the "cats" channel. There could also be a "dogs" channel, but I will not receive those messages, since I am only subscribed to "cats".
  • broker - The broker maintains the state of which websockets are subscribe to which channels. Each message is published to the broker on a channel. The broker then looks up all websockets currently subscribed to that channel and forwards the message to them.

Getting Started

Install

npm i -s pubsub-ws

Set up an http server for the websockets.

import http from 'http';
import WebSocket from 'ws';
import { createBroker } from 'pubsub-ws';

// ----- Set up the websocket server and pubsub broker -----

const server = http.createServer(); // https server is also supported

Create the pubsub-ws broker.

The second argument to createBroker is the getChannel function, which is called each time a websocket upgrade request is received. getChannel receives the http request and expects back a channel. The websocket is subscribed to this channel. We can subscribe all websockets to the same channel (as in this example) or use data in the request to intelligently subscribe different websockets to different channels. The latter is shown in the authentication example, further down in the readme.

const broker = createBroker(server, (request) => {
  return Promise.resolve('myChannel');
});

server.listen(7123);

Test by connecting a websocket and publishing data to the channel

const ws = new WebSocket('ws://localhost:7123');
ws.on('open', () => console.log('ws open'));
ws.on('message', (data) => console.log(`received message: ${data}`));

setInterval(() => {
  broker.publish('myChannel', 'test data');
}, 2000);

Authentication

The getChannel function (called each time a websocket upgrade request is received) can be used to authenticate clients. Reject the returned Promise if the request is unauthenticated. Below is a typescript example using session authentication with the express-session middleware to parse a passport js session.

import session from 'express-session';
import { createBroker } from 'pubsub-ws';

const sessionParser = session({
  // your session options here
});

const authenticateAndGetChannel = (req: any) => {
  return new Promise<string>((resolve, reject) => {
    sessionParser(req, {} as any, async () => {
      if (!req.session?.passport?.user) {
        logger.info('Unauthenticated websocket request');
        reject();
      } else {
          resolve(user); // in this example, each user subscribes to its own channel
      }
    });
  });
}
const broker = createBroker(server, authenticateAndGetChannel));

More Examples

express-shared-port - Websockets, express APIs, and express static files all on the same port (server). Includes an example of connecting websockets from a frontend html page.