1.0.6 • Published 4 years ago

stc-emitter v1.0.6

Weekly downloads
1
License
MIT
Repository
github
Last release
4 years ago

Introduction

stc-emitter (Server to client emitter) sends the events to the client. The client can listen the events using EventSource API. It is excellent when the client has to listen the events but has no need to emit the events.

Installation

$ npm install stc-emitter

Usage

Server can send the events like this:

const express = require('express');
const { ListenerClient, Audience } = require('stc-emitter');

const app = express();
const scoreAud = new Audience();
foo.on( 'bar', baz => scoreAud.deliver('scoreUpdate', baz) );

app.get('/score-emitter', (req, res) => {
    scoreAud.add(res);
});

If sending events to each client separately is desired:

const express = require('express');
const { ListenerClient, Audience } = require('stc-emitter');

const app = express();

app.get('/score-emitter', (req, res) => {
    const client = new ListenerClient(res);

    foo.on('bar', sendEvent);
    function sendEvent(baz) {
        client.emit('scoreUpdate', baz);
    }

    // Note: Audience takes care of ending the respone automatically,
    // if you are using ListenerClient, you have to take care of it.
    res.on('close', () => {
        foo.off('bar', sendEvent);
        res.end();
    });
});

Client can listen events like this:

const source = new EventSource('/score-emitter');
source.addEventListener('scoreUpdate', e => {
    console.log(e.data);
});

For complete client-side guide visit MDN.

API

See API documentation.