SSE-Pusher
Simple server-sent events (SSE) for Connect and Express.
Installation
$ npm install --save sse-pusher
API
var ssePusher = ; var push = ; // instantiation variant 1var push = ssePusher; // instantiation variant 2
push([event,] data)
Pushes an optionally typed (i.e., using the event
parameter) event to all connected SSE clients.
Parameters:
event
- event type, must be a string;data
- event data, can be anything that can be serialized usingJSON.stringify()
. More precisely, anything that is not a string, number or boolean will be serialized usingJSON.stringify()
.
push.handler([mountPath])
Returns a function that can be used both as a Connect/Express middleware and an Express route handler.
Parameters:
mountPath
- path where the Connect/Express middleware shall be mounted (e.g.,/some/path
).
Usage
Server-side
First, you have to load the package a instantiate a new SSE-Pusher:
// load package:var ssePusher = ; // instantiate a new SSE-Pusher:var push = ;
Afterwards, you have to "wire" the SSE-Pusher with you HTTP framework of choice (i.e., Connect or Express):
var app = || ; // install the pusher as a Connect/Express middleware:app; // variant 1app; // variant 2 // install the pusher as an Express route handler:app;
Finally, using push(event, data)
or push(data)
you can then start pushing data to connected SSE clients:
// push some data:; // push some data without specifying an event name:;
Client-side
On the client (i.e., the Web browser) you may then listen to the server-side emitted messages using the following code:
var es = 'http://localhost:3000/some/path'; // when using push('hello') on the server:es { console; // logs 'hello'}; // when using push('greeting', 'world') on the server:es;