Code Monkey home page Code Monkey logo

express-longpoll's Introduction

Build Status npm version

Lightweight long polling module for express.js

Description

Sets up basic long poll with subscribe and publish functionality.

Install

$ npm install -S express-longpoll

Usage

Basic initalization

var express = require('express');
var app = express();
var longpoll = require("express-longpoll")(app)
// You can also enable debug flag for debug messages
var longpollWithDebug = require("express-longpoll")(app, { DEBUG: true });

Quick-start code

Server - server.js

var express = require('express');
var app = express();
var longpoll = require("express-longpoll")(app);

// Creates app.get("/poll") for the long poll
longpoll.create("/poll");

app.listen(8080, function() {
    console.log("Listening on port 8080");
});

var data = { text: "Some data" };

// Publishes data to all clients long polling /poll endpoint
// You need to call this AFTER you make a GET request to /poll
longpoll.publish("/poll", data);

// Publish every 5 seconds
setInterval(function () { 
    longpoll.publish("/poll", data);
}, 5000);

Client - index.js (with jQuery)

var poll = function () {
    $.ajax({
       url: "localhost:8080/poll",
       success: function(data){
           console.log(data); // { text: "Some data" } -> will be printed in your browser console every 5 seconds
           poll();
       },
       error: function() {
           poll();
       },
       timeout: 30000 // 30 seconds
    });
};

// Make sure to call it once first,
poll();

###longpoll.create(url, [options])
Sets up an express endpoint using the URL provided.

var longpoll = require("express-longpoll")(app);

longpoll.create("/poll");
longpoll.create("/poll2", { maxListeners: 100 }); // set max listeners

###longpoll.create(url, middleware, [options])
Set up an express endpoint using the URL provided, and use middleware.

var longpoll = require("express-longpoll")(app);

longpoll.create("/poll", function (req,res,next) {
    // do something
    next();
});

###longpoll.publish(url, data)
Publishes data to all listeners on the url provided.

var express = require('express');
var app = express();
var longpoll = require("express-longpoll")(app);

longpoll.create("/poll");

longpoll.publish("/poll", {});
longpoll.publish("/poll", { hello: "Hello World!" });
longpoll.publish("/poll", jsonData);

###longpoll.publishToId(url, id, data)
Publish data to a specific request. See the basic example on how to use this effectively.

Works with Routers

var express = require('express');
var router = express.Router();
// with router
var longpoll = require("express-longpoll")(router);

longpoll.create("/routerpoll");

router.get("/", (req, res) => {
    longpoll.publish("/routerpoll", {
        text: "Some data"
    });
    res.send("Sent data!");
});

module.exports = router;

Can publish to any endpoint, from anywhere.

server.js - create here

var longpoll = require("express-longpoll")(app);
longpoll.create("/poll");

route.js - use here

var longpoll = require("express-longpoll")(router);
// Can publish to any endpoint
longpoll.publish("/poll");

Using Promises

longpoll.create("/poll")
  .then(() => {
    console.log("Created /poll");
  })
  .catch((err) => {
    console.log("Something went wrong!", err);
  });
  
longpoll.publish("/poll", data)
  .then(() => {
    console.log("Published to /poll:", data);
  })
  .catch((err) => {
    console.log("Something went wrong!", err);
  });

Sample clientside code to subscribe to the longpoll

###Client using jQuery

var subscribe = function(url, cb) {
        $.ajax({
            method: 'GET',
            url: url,
            success: function(data) {
                cb(data);
            },
            complete: function() {
                setTimeout(function() {
                    subscribe(url, cb);
                }, 1000);
            },
            timeout: 30000
        });
    };
    
subscribe("/poll", function (data) {
  console.log("Data:", data);
});

subscribe("/poll2", function (data) {
  console.log("Data:", data);
});

express-longpoll's People

Contributors

nimast avatar samcyanide avatar yehya avatar

Stargazers

 avatar

Watchers

 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.