Saturday 6 May 2017

Publish Subscribe using Nodejs and PubNub service

I am trying to test PubNub pub/sub model using Nodejs.

Currently, nodejs and npm is setup and running on windows.

and I have simple server setup in app.js file.

Where does exactly publish and subscribe code go in order to test the functionality of publish and subscribe? like: server publishes 'hello world' and lets say 2 users open browser and navigate to http://localhost:8888 and get the message on a browser "Hello World".

pubnub code (I am trying to add to nodejs project)

var PubNub = require('pubnub')

// PubNub = require('pubnub');      ES5
import PubNub from 'pubnub';        ES6

var pubnub = new PubNub({
    subscribeKey: "mySubscribeKey",
    publishKey: "myPublishKey",
    secretKey: "secretKey",
    ssl: true
})

pubnub.subscribe({
    channels: ['my_channel'],
    withPresence: true // also subscribe to presence instances.
})


pubnub.publish(
    {
        message: { 
            such: 'object'
        },
        channel: 'my_channel',
        sendByPost: false, // true to send via post
        storeInHistory: false, //override default storage options
        meta: { 
            "cool": "meta"
        }   // publish extra meta with the request
    }, 
    function (status, response) {
        if (status.error) {
            // handle error
            console.log(status)
        } else {
            console.log("message Published w/ timetoken", response.timetoken)
        }
    }
);

my directory structure:

app.js
index.html
package.json (I have only one dependency here: pubnub)

my app.js code

var http = require("http");
var fs = require("fs");
var PubNub = require("pubnub");

function server404Response (response) {
    response.writeHead(404,{'contentType':'text/plain'});
    response.write("404, Page Not Found Error");
    response.end();
}

function onRequest(request,response) {
    if(request.method == 'GET' && request.url == '/'){

         response.writeHead(200,{'contentType':'text/html'});
         fs.createReadStream("./index.html").pipe(response);

    }else{
        server404Response(response);
    }
}


http.createServer(onRequest).listen(8888);
console.log("Server is running");

my index.html code

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Home Page of the Application</title>
</head>
<body>
Hello, Home Page of the Application
</body>
</html>

My first project on nodejs (I am fairly new to nodejs environment).



via Murlidhar Fichadia

No comments:

Post a Comment