GithubHelp home page GithubHelp logo

siathalysedi / susie Goto Github PK

View Code? Open in Web Editor NEW

This project forked from mtharrison/susie

0.0 3.0 0.0 310 KB

Server-sent events with hapi

License: BSD 3-Clause "New" or "Revised" License

JavaScript 100.00%

susie's Introduction

SuSiE - Server-Sent Events with hapi

Build Status

Above example under /examples. Start with npm start

This is a plugin that adds simple Server-Sent Events (aka EventSource) capabilities to hapi. It decorates the reply() interface with a new method reply.event(). You can send individual events as objects, or you can simply pass a stream and some options and SuSiE will make things work as you expect.

You probably already know this but install it with: npm install --save susie

Usage

First load and register the plugin:

server.register(require('susie'), function (err) {
    ...
});

With event objects

In a route handler you can now call reply.event() to start an SSE response:

server.route({
    method: 'GET',
    path: '/',
    handler: function (request, reply) {

        reply.event({ data: 'my data' });
    }
});

The first time you call reply.event(), appropriate HTTP response headers will be sent, along with your first event. Subsequent calls to reply.event() will send more events.

server.route({
    method: 'GET',
    path: '/',
    handler: function (request, reply) {

        reply.event({ id: 1, data: 'my data' });

        setTimeout(function () {

            reply.event({ id: 2, data: { a: 1 } }); // object datum
        }, 500);
    }
});

If any of your datum are objects, they will be stringified for you. Make sure to parse them again in the client, if you're expecting JSON.

With a readable stream

A really nice way to provide an EventSource is using a ReadableStream. This is really simple with SuSiE. Just call reply.event(stream):

server.route({
    method: 'GET',
    path: '/',
    handler: function (request, reply) {

        var Readable = require('stream').Readable;
        var rs = Readable();

        var c = 97;
        rs._read = function () {
            rs.push(String.fromCharCode(c++));
            if (c > 'z'.charCodeAt(0)) rs.push(null);
        };

        reply.event(rs);
    }
});

http://cl.ly/d5XT/Screen%20Shot%202015-09-13%20at%2015.50.25.png

Each chunk coming off the stream will be sent as an event. The content of the chunk will be the data parameter. You can provide an optional event option and id generator. By default the id will be the number of chunks received:

server.route({
    method: 'GET',
    path: '/',
    handler: function (request, reply) {

        var i = 0;
        var generateId = function (chunk) { return i += 10; }
        reply.event(stream, null, { event: 'update', generateId: generateId });
    }
});

Object mode streams

If the stream is in objectMode, each object that comes off the stream will be stringified and the resulting string will be used as the data parameter. See example under examples for example.

Considerations

How do I finish a SSE stream for good?

In the SSE spec, it says that when the HTTP response ends, the browser will try to reconnect, sending another request to the endpoint. You may want this. Or you may really want to stop to the events being streamed altogether.

When you call reply.event(null) or your stream emits its end event, the HTTP response will conclude. However, SuSiE will send one last event to the browser before it closes. You should listen for this end event in your client code and close the EventSource, before the browser attempts to reconnect:

<script>
    var source = new EventSource('/events');
    ...
    source.addEventListener('end', function (event) {
    
        this.close();
    });
</script>

susie's People

Contributors

mtharrison avatar g-div avatar vdeturckheim avatar

Watchers

Arnstein Henriksen avatar James Cloos avatar  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.