Coder Social home page Coder Social logo

thachpv91 / better-sse Goto Github PK

View Code? Open in Web Editor NEW

This project forked from matthewwid/better-sse

0.0 1.0 0.0 767 KB

⬆ Dead simple, dependency-less, spec-compliant server-side events implementation for Node, written in TypeScript.

License: MIT License

TypeScript 100.00%

better-sse's Introduction

Better SSE

A dead simple, dependency-less, spec-compliant server-side events implementation for Node, written in TypeScript.

This package aims to be the easiest to use, most compliant and most streamlined solution to server-side events with Node that is framework agnostic and feature rich.

Please consider starring the project on GitHub ⭐.

Why use Server-sent Events?

Server-sent events (SSE) is a standardised protocol that allows web-servers to push data to clients without the need for alternative mechanisms such as pinging or long-polling.

Using SSE can allow for significant savings in bandwidth and battery life on portable devices, and will work with your existing infrastructure as it operates directly over the HTTP protocol without the need for the connection upgrade that WebSockets require.

Compared to WebSockets it has comparable performance and bandwidth usage, especially over HTTP/2, and natively includes event ID generation and automatic reconnection when clients are disconnected.

Highlights

  • Compatible with all popular Node HTTP frameworks (http, Express, Koa, Fastify, etc.)
  • Fully written in TypeScript (+ ships with types directly).
  • Thoroughly tested (+ 100% code coverage!).
  • Comprehensively documented with guides and API documentation.
  • Channels allow you to broadcast events to many clients at once.
  • Configurable reconnection time, message serialization and data sanitization (but with good defaults).
  • Trust or ignore the client-given last event ID.
  • Automatically send keep-alive pings to keep connections open.
  • Add or override the response status code and headers.
  • Fine-grained control by either sending individual fields of events or sending full events with simple helpers.
  • Pipe streams and iterables directly from the server to the client as a stream of events.
  • Support for popular EventStream polyfills event-source-polyfill and eventsource-polyfill.

See a comparison with other Node SSE libraries in the documentation.

Installation

# npm
npm install better-sse

# Yarn
yarn add better-sse

# pnpm
pnpm add better-sse

Better SSE ships with types built in. No need to install from @types for TypeScript users!

Usage

The following example shows usage with Express, but Better SSE works with any web-server framework (that uses the underlying Node HTTP module).

See the Recipes section of the documentation for use with other frameworks and libraries.


Use sessions to push events to clients:

// Server
import {createSession} from "better-sse";

app.get("/sse", async (req, res) => {
	const session = await createSession(req, res);

	session.push("Hello world!");
});
// Client
const sse = new EventSource("/sse");

sse.addEventListener("message", ({data}) => {
	console.log(data);
});

Use channels to send events to many clients at once:

import {createSession, createChannel} from "better-sse";

const channel = createChannel();

app.get("/sse", async (req, res) => {
	const session = await createSession(req, res);

	channel.register(session);

	channel.broadcast("A user has joined.", "join-notification");
});

Loop over sync and async iterables and send each value as an event:

const session = await createSession(req, res);

const list = [1, 2, 3];

await session.iterate(list);

Pipe readable stream data to the client as a stream of events:

const session = await createSession(req, res);

const stream = Readable.from([1, 2, 3]);

await session.stream(stream);

Check the API documentation and live examples for information on getting more fine-tuned control over your data such as managing event IDs, data serialization, event filtering, dispatch controls and more!

Documentation

API documentation, getting started guides and usage with other frameworks is available on GitHub.

Contributing

This library is always open to contributions, whether it be code, bug reports, documentation or anything else.

Please submit suggestions, bugs and issues to the GitHub issues page.

For code or documentation changes, submit a pull request on GitHub.

Local Development

Install Node:

curl -L https://git.io/n-install | bash
n auto

Install pnpm:

npm i -g pnpm

Install dependencies:

pnpm i

Run tests:

pnpm t

License

This project is licensed under the MIT license.

better-sse's People

Contributors

matthewwid avatar abhi12299 avatar

Watchers

James Cloos avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.