Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

node.js server and client sideo code to connect

node.js server and client sideo code to connect


Im trying to set up a node.js server to send messages to the client, which will then display the messages using a jquery notification library, I'm using this notifcation library if anyone's interested:

At the minute I have a postgres database set up with a table which has a a trigger on it to write to a listener.

The trigger is as follows:

    PERFORM pg_notify('watchers', TG_TABLE_NAME || ',msg,' || NEW.msg );
    RETURN new;
$$ LANGUAGE plpgsql;

Then I have a node.js server as follows:

var pg = require ('pg');

var pgConString = "pg://aydin:[email protected]/test"

var app = require('http').createServer(handler)
    , io = require('').listen(app)
    , url = require('url')


function handler (request, respsonse) {
    var client = new pg.Client(pgConString);
    client.query('LISTEN "watchers"');
    client.on('notification', function(msg) {

function sendMessage(message) {
    io.sockets.emit('notification', {'message': message});

Then I have some client Code as follows:

This doesn't work, it seems the node.js never receives the postgres notifications, I think this is because I am using the function handler and I'm not actually firing any requests to it from the client code. I'm not sure how to do this and whether it is the correct way? Is there a function on which can fire on connections and not requests?

And am I even doing it the right way round? should there be a server on the client side which node.js sends messages to? How does it know when a client is available? Any help or pointers to tutorials would be much appreciated. Thankyou.

Problem courtesy of: Aydin Hassan


You're not actually setting up your database connection until the client sends an HTTP request. It looks like that may never happen due to same-origin issues (your client code appears to be coming from somewhere other than the server you've shown).

In any case, you probably want to set up the connection in response to a "connection" event from io.sockets (i.e. move the stuff that's currently in the HTTP request handler there). That's how it "knows when a client is available". Or maybe you should be doing it as part of initialization. Your client-side code seems OK, but it's out of context so it's hard to tell whether it really fits your needs.

Solution courtesy of: ebohlman


View additional discussion.

This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

node.js server and client sideo code to connect


Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription