Nodejs and a simple push notification server


Hey dudes, In this post I will show you how to create a simple push notification server using nodejs and Generally if we want update some contents inside  a web application, we are used to refreshing the page using a javascript timer or simply we do some iterated AJAX requests to a web service so we can fetch constantly updated data. This could be a good solution for a small number of users , but what is going to happen if you got a big amount of geeks at the same time on your website?

As you should know, you can get the weight of any AJAX request summing the header (client) request + the header (server) response + the weight of data retrieved (you can get more info here websocket performance). So if you have a huge number of users on your web application doing many AJAX requests trying to load updated content, even if there are some AJAX requests that could not contain any new data, your server is forced to support a big number of unnecessary requests simulating a long polling connection. To solve this big issue you may have just two solution:

  1. you are GOOGLE so your have a big server farm that allows you to do any kind of rubbish
  2. you can smartly use a crossbrowser solution building a clean push notification server

I will show you how to build a simple and clean pushing notification server so let’s start to code. First you need to install nodejs on your server. Then for this example we need to import and xml2js nodejs modules in our project. You can use “npm” (node package manager) command by your console to install any kind of nodejs module like this:

$ npm install
$ npm install xml2json

So you have to create the server.js file that contains all the nodejs javascript that will run on the server. Here it is the source code:

var app = require('http').createServer(handler),
  io = require('').listen(app),
  parser = new require('xml2json'),
  fs = require('fs');

// creating the server ( localhost:8000 )

console.log('server listening on localhost:8000');

// on server started we can load our client.html page
function handler(req, res) {
  fs.readFile(__dirname + '/client.html', function(err, data) {
    if (err) {
      return res.end('Error loading client.html');

// creating a new websocket to keep the content updated without any AJAX request
io.sockets.on('connection', function(socket) {
  // watching the xml file
  fs.watchFile(__dirname + '/example.xml', function(curr, prev) {
    // on file change we can read the new xml
    fs.readFile(__dirname + '/example.xml', function(err, data) {
      if (err) throw err;
      // parsing the new xml data and converting them into json file
      var json = parser.toJson(data);
      // send the new data to the client
      socket.volatile.emit('notification', json);


Then you are ready to create a simple example.xml file containing all your data:

<?xml version="1.0" encoding="ISO-8859-1"?>
    <sample>Hello world!</sample>

At last you are free to build your frontend page client.html where your data will be pushed anytime your example.xml will change.

     * Author:      Gianluca Guarini
     * Contact:
     * Website:
     * Twitter:     @gianlucaguarini
        <title>Push notification server</title>
        <div id="container">Try to change your xml data to update this content</div>
    <script src=""></script>
    <script src=""></script>
    // creating a new websocket
    var socket = io.connect('http://localhost:8000');
    // on every message recived we print the new datas inside the #container div
    socket.on('notification', function (data) {
        // convert the json string into a valid javascript object
        var _data = JSON.parse(data);

        $('time').html('Last Update:' + new Date());

I made this video so you can see how it should work:

This is a simple and crossbrowser solution just because thanks to, we create a full duplex connection between the html page and the server so it will push new data only when the xml file changes, by using the new websocket API and then the flash technology for the fallback ( read support for more info ).

Download the files used in this tutorial

If you liked this post you can read my new article about how to bring your Nodejs push notification server to the next level reading from a MySql database.


  • i have a little problem, can you help me please?
    text in web didn’t change to “hello world” and i got this on server.js

    debug – setting request GET /
    debug – setting poll timeout
    debug – discarding transport
    debug – cleared close timeout for client 15051029411184320447
    debug – clearing poll timeout
    debug – xhr-polling writing 8::
    debug – set close timeout for client 15051029411184320447

  • Hey Gianluca,
    I am trying out your example and everything works only on localhost. In another words, the nodeJS or didn’t work with remote clients, anyone who isn’t on the same machine. I am quite puzzled at the moment.

    I tried to host it on localhost on Windows XP, and have one of my friend access through the Lan, or I host on a Node server with CentOS 5.5 and tried to access it.
    I would end up with following
    info – started
    debug – served static content /
    No matter how I modify the example.xml, both log and content do not change at all.

    I tried to get rid of all the file change checking and parsing, just plain
    socket.volatile.emit( ‘notification’ , ‘test’);
    and it worked…so either fs or parser failed, I suspected that the fs module has some issues but this doesn’t feel right because it works with localhost.
    Do you have any ideas in mind about why this might happen?

    • Resolved the issue just now. Sorry for posting the long post. But stuck at fs now. I’m trying to see if this is related to some bug in fs module.

      throw errnoException(errno, ‘watch’);
      Error: watch ENOSYS
      at errnoException (fs.js:636:11)
      at FSWatcher.start (fs.js:663:11)
      at (fs.js:691:11)
      at SocketNamespace. (/server.js:27:6)

      • Hello Tim,
        I am having the same problem that you had…remote client do not work. My local host is ok. You mentioned in your next post that you have resolve the issue but you did not post your answer.
        May I know how you solve this problem?

  • Hey Dude,

    this was excellent work, i got an error

    match = req.url.substr(0, resource.length);
    i’m using Debian 6 OS.

    can you please suggest me something.

    Nitin ray

  • Pingback: NodeJS « AgNetPro

  • Grande. Funziona a meraviglia.
    Unico appunto, a riga 27,
    Nodejs si incazza e vuole al posto di:

    fs.watchFile( ‘example.xml’, function ( curr, prev ) {

    questa: ‘example.xml’, function ( curr, prev ) {

    Altrimenti butta un throw.

    Grazie della guida.

  • i try this example and… it works but i got this console log

    data is null
    [Parar en este error]


    can you tell me what’s wrong?

    • The problem is fixed, I was using watchFile API instead of watch API, right now I just update the article and the repository.
      Thanks to Daniele for the tip.

  • Cool, thanks a lot.. works perfect.

    But think you have to change the client code var socket = io.connect(‘http://localhost’); to var socket = io.connect(‘http://localhost:8000’);

  • why do you have “node module” folder into folder..which extra package are you installing … i followed you blog and write code but it is giving me error!!! but after runing ur code which u attach with this blog this working fine.. only difference in extra node module folder(means extraa package) in folder..

      • Got it.. you install package in to…which you forgot to tell in blog!!! BTW good blog i was searching such simple tutorial for …thnks a lot!!

        • It is in the first instruction of this tutorial “npm install”! The default module, installable by npm, it is already with package in to I am glad you’ve appreciated the tutorial :)

  • Hey,
    I just wondering if you can give some gud and simple tutorial about how to use ajax and node.js together.. i unable to find gud and correct tutorial abt it. if u can thn plz write some gud tutorial for wil realy helpful..

  • Great work dude.
    Actually, I’ve something complex a bit. I want the notifications to be delivered just for specific users (friends). How could that be? Friends are stored in a “Friend” table which contains each “member_id” with his “friend_id”s. Some keywords or general idea maybe enough for me to get started.

  • I have test your code and it works perfect. However, I have one problem that I can’t fix.

    I need to listen instead of example.xml one file designated on the fly. That is, if the user open a socket on localhost:8000/site/entity/1234/ then, the file I will listen to is:


    How can I do it? Do you have any idea?

  • Excellent! Was thinking to myself: how does Apple’s push notifications work. Something must be listening. Can’t we do the same thing in the browser? Can’t the client run a server? So I started out on a search, specifically for use with node.js and came across this. Seems like the perfect starting point for something I want to do. Thanks!

    • I know one thing for sure. Apple will make you cry πŸ˜€

      I’ve used PushSharp in my previous app but since my back end stack is built on top of nodejs I’m looking for good place/app to push notifications from server to APN and GCM

  • This seems so cool – just not working for me! :(

    I followed the instructions here, except that I changed the listening port (to 8888). When I hit the port, I get the message “Try to change your xml data to update this content”, so the (Linux Red Hat) server’s running OK. Now when I change the content of the XML file and save it on the server, nothing happens on the client browser. On the console, I do see heartbeat checks and, when I edit the file and save it, I see messages of this format:
    debug – websocket writing 5:::{“name”:”notification”,”args”:[{“test”:{“sample”:[“Hello! Changed? No? Come on!”]},”time”:”2012-09-07T14:41:45.884Z”}]}.
    But I don’t see any change on the client browser.

    I don’t know if this matters, but among the console messages, I see this:
    debug – websocket writing 2::
    debug – set heartbeat timeout for client ID7HJqkn0WIwHd9ULRrI
    debug – got heartbeat packet
    debug – cleared heartbeat timeout for client ID7HJqkn0WIwHd9ULRrI
    Meaning, the number after “websocket writing…” is different where it seems to checking the heartbeat from where it is writing the notification.

    What am I doing wrong?

  • Hello world!

    After taking out , the example works on my CentOS and WinXP machines.

    Thanks Guarini.

  • Indeed tutorial is excellent!

    But it not working for me! I am using Window 7 and Google Chrome. Whenever I change example.xml content in in browser does not changing at all.

    Any comments?

    • I think it is not a problem related to the tutorial itself but It could be more related to your windows7 environment. Please check if you have all the assets installed correctly to run this example.

    • Agreed, great tutorial. Although I am having the same issue on Win7 Pro/Chrome (v23.0.1271.64).

      Date/Time is updating everytime the XML is changed, but the other content in the browser doesn’t change. I can however see my updated text in the log … it just never gets pushed to the browser.

      Any thoughts?

      • Scratch that – I have figured it out. I removed the elements from my xml just to leave:


        This now works.

  • Thanks for the tutorial. it is helpful to me however, my problem is that whenever some records are inserted in MySQL table. i want to notify to particular user who is associated with that record. so, is it possible to keep watch/trigger on mysql data tables rather than file.


    • I have received many requests to show you how to realize push notification polling on a db so I am planning to make a new tutorial. In the meanwhile I could say that the only way that I know to watch a MySQL db is by a timer that could be set trough node anyway I would avoid this approach and I suggest you a Redis db for this kind of stuff.

  • Very nice tutorial, straight to the point.

    But, (and this is missing on most tuts) how to send data to different clients that are connected? How to send right push to the right client with the right data?

    Please could you help on this matter?

    thanks again!

    • Hi thank you R.Dylan, this is just a demo to show you how node.js is able to broadcast data to different devices connected at same time on the same web page (this is perfect for news websites and so on..). Starting from this tutorial you could easily try to send the right data to each client connected using user credentials ( like username and password, or client id for example), obviously this should be done serverside thanks to node.js that deals with each client connection (you can collect all the connections in an Array or an object…). Soon I will publish another tutorial about Push notification from a MySql database and probably it could help you to understand what you could do with node.js under the hood!
      Let’s keep in touch.

  • Pingback: Push notification server streaming on a MySQL database | Gianluca Guarini's Blog

  • Hi, It’s good tutorial… I have few questions, some are following..
    How many web client(web socket) connections can persist by this server (depends on host machine, i guess)? Suppose if it is 1000, how to overcome?
    and do you know, what is the life span of web socket persistance?

    • Hi and thanks for the interesting questions:

      How many web client(web socket) connections can persist by this server (depends on host machine, i guess)?

      Yes you are right, the number of connection that a server could support depends on the host machine but I suggest you to read this post for a deeper explanation of that.

      Suppose if it is 1000, how to overcome?

      You shouldn have big problems, Anyway you must stay under the ~3000 connections at same time

      and do you know, what is the life span of web socket persistance?

      A websocket is persistent by its definition . A websocket connection is closed when a user leaves the application (when the browser tab gets closed) or you can close it from the server after a certain period of time.

      I hope it was clear enough πŸ˜‰

      • Your server is notified of the Node server event with the handler.

        Is there any other way for the server to be notified of an event sent by the Node server ?

        My Node server is doing a:
        io.sockets.emit(‘message’, “The NodeJS http server says firstname: ” + postedData.firstname + ” lastname: ” + postedData.lastname);
        in an http handler triggered on a curl request.

        But the server is not picking up the message.

  • Hi I have a small issue, I am running this under SuSE Linux, I get this error if I edit the xml and refresh the page:

    debug – client authorized for
    debug – websocket writing 1::
    debug – websocket writing 5:::{“name”:”notification”,”args”:[{“test”:{“sample”:[“Hi there friend! Whts up”]},”time”:”2013-02-07T05:34:35.030Z”}]}

    throw ex;
    Error: Text data outside of root node.
    Line: 6
    Column: 10
    Char: H
    at error (/node_modules/xml2js/node_modules/sax/lib/sax.js:616:8)
    at strictFail (/node_modules/xml2js/node_modules/sax/lib/sax.js:636:22)
    at Object.write (/node_modules/xml2js/node_modules/sax/lib/sax.js:933:13)
    at Parser.exports.Parser.Parser.parseString (/node_modules/xml2js/lib/xml2js.js:221:31)
    at Parser.__bind [as parseString] (/node_modules/xml2js/lib/xml2js.js:6:61)
    at /noderoot/push_notification_server/server.js:32:10
    at fs.readFile (fs.js:176:14)
    at Object.oncomplete (fs.js:297:15)

    I am not using localhost however, I am using a different IP in the html page:
    var socket = io.connect(“”);

    I suspect this could be causing the problem, any ideas on how to do this but not via localhost? Thanks!

    • I exactly have same error above. Do you have any idea?

      *Sorry, please delete my previous comment. I intended to reply this comment.*

      • Hi I don’t know what are you doing there , but I have tried it on my ubuntu 12.10 and everything works correctly, Have you set the right port inside the server.js file ( app.listen(8000); ) ? What does it mean “I am not using localhost however, I am using a different IP in the html page”? Which nodejs version are you using?

    • We’ve got the same problem and i think problem is caused by inotify under Linux. or fs.watchFile uses
      On Linux systems, this uses inotify.

      So I logged the events, and i saw sends 2 times change event in one time. So first change is true and it processes the data but second one is not true and it comes null.

      So you cannot use this function because, it breaks the websocket connection when you use try catch

  • Same guy as above ^^

    Error I seem to be getting is:

    if ( err ) throw err;
    Error: ENOENT, open ‘example.xml’

    However the example.xml file is in the same directory as server.js, what could be wrong?

  • Hi. I have problem running this app on the other computers in my network and on phone, which is connected via wireless on my network. It is only work on localhost, where is server running. I’m not familiar with javascript, so do you have any suggestions to solve this problem?


    • Ciao Luka,
      if you cannot connect your mobile to localhost, just use an emulator on your computer or run the script on your own server directly online. I am sorry but this is an advanced javascript hack and probably you could start from something simpler. Good luck

  • Pingback: Why to consider Node.js for your mobile web apps? - Blog

  • You really make it appear so easy along with your presentation however I find this topic to be actually something which I feel I might by no means understand. It sort of feels too complex and extremely vast for me. I am having a look ahead in your next post, I will try to get the dangle of it!

  • When I changed the xml file I got this error in the console (I’m using FF 20 on Windows 7)

    result.time = new Date();
    TypeError: Cannot set property ‘time’ of null
    at Parser. (C:\opt\cygwin\exe\home\george\dev\node\server.js:39:17)
    at Parser.EventEmitter.emit (events.js:95:17)
    at Parser.exports.Parser.Parser.parseString (C:\opt\cygwin\exe\home\george\dev\node\node_modules\xml2js\lib\xml2js.js:254:14)
    at Parser.parseString (C:\opt\cygwin\exe\home\george\dev\node\node_modules\xml2js\lib\xml2js.js:6:61)
    at C:\opt\cygwin\exe\home\george\dev\node\server.js:32:14
    at fs.js:266:14
    at Object.oncomplete (fs.js:107:15)

    • Which nodejs version are you using? To me it looks like a really easy problem due to your dev environment. Have you also tried an npm update inside the project folder?

  • Hello Gianluca,

    I am sure there is a simple fix but I am stuck at the moment. I tried your sample but it only works for local client within my PC. I cannot get the push notification to work on a remote cleint. How to resolve this problem?
    Thank you in advance for your help.

  • Thanks for the Excellent example! However i had issue when i run it 2nd times and displayed the error msg below:

    throw er; // Unhandled ‘error’ event
    Error: Text data outside of root node.
    Line: 6
    Column: 10
    Char: w
    at error (/Users/admin/Sites/opc/node_modules/xml2js/node_modules/sax/lib/sax.js:616:8)
    at strictFail (/Users/admin/Sites/opc/node_modules/xml2js/node_modules/sax/lib/sax.js:636:22)
    at Object.write (/Users/admin/Sites/opc/node_modules/xml2js/node_modules/sax/lib/sax.js:933:13)
    at Parser.exports.Parser.Parser.parseString (/Users/admin/Sites/opc/node_modules/xml2js/lib/xml2js.js:264:29)
    at Parser.parseString (/Users/admin/Sites/opc/node_modules/xml2js/lib/xml2js.js:77:45)
    at /Users/admin/Sites/opc/server.js:32:14
    at fs.js:266:14
    at Object.oncomplete (fs.js:107:15)

    It was no prob when execute 1st time and it can update immediate. Just happen 2nd time update the xml file and appear the error.

    • I’m having the same problem, Have you found a fix yet ?

      Thanks for the great article :)
      I had to add ‘__dirname +’ to both fs functions to get it working. you might wanna mention that on your post.also there is no any element named ‘time’ in your ‘client.html’ file so we won’t be able to view the time.

      • Thanks for your tutorial Gianluca, great work.

        I’ve got the same same problem when parsing the file twice and I’ve solved it by adding this line:



        parser.parseString( data );

    • Grazie for a *very* helpful and clear tutorial!

      I was also getting the “Error: Text data outside of root node.” exception.

      I put the notification into the parseString callback (and deleted the original addListener function) and it works great now. Maybe xml2js has changed? Here’s my new socket code:

      // creating a new websocket to keep the content updated without any AJAX request
      io.sockets.on( ‘connection’, function ( socket ) {
      // watching the xml file __dirname + ‘/example.xml’, function ( curr, prev ) {
      // on file change we can read the new xml
      fs.readFile( __dirname + ‘/example.xml’, function ( err, data ) {
      if ( err ) throw err;
      // parsing the new xml data and converting them into json file
      parser.parseString( data, function(err, result) {
      if ( err ) throw err;
      result.time = new Date();
      socket.volatile.emit( ‘notification’ , result );

  • Hi Gianluca,

    I came across your blog after going through lot of futile searches on Google. This is exactly what I was looking for. It is really very helpful. Thank you so much for the excellent write up and the code. :)



  • ciao Gianluca,
    Ho visto che sei Italiano ! Ho trovato il tuo esempio molto, molto interessante. Ti ringrazio !
    I will download the sample code and give it a try, as I’m using mvc 4 with c# and lots of Html5 and jQuery techniques.
    ciao ciao.

  • Hi Gianluca,
    Thanks a lot for your explain. You help me a lot to understand the node.js
    But, I have on question.
    I want to call one php function what load the html view, but I don’t know how to write the path in this case. Do you have any idea?

    For example, you call index.html in this form:
    // on server started we can load our client.html page
    function handler ( req, res ) {
    fs.readFile( __dirname + ‘/client.html’ ,
    function ( err, data ) {
    if ( err ) {
    console.log( err );
    return res.end( ‘Error loading client.html’ );
    res.writeHead( 200 );
    res.end( data );

    But, how can I call a PHP function that is in CodeIgniter Framework. Server.js I have at node_server folder, but the php function is in application/module_name/controller_name/function_name.
    When I try to go with __dirname, it go with C:/xampp/ etc. not with localhost.

    Can you help me in this case?


    • Hi Erman,
      what do you mean saying “I want to call one php function…”? I think in general that a nodejs app should not be combined with other serverside languages this it definitely a bad practice! If you need data coming from other scripts or whatever web services I suggest you to use a JSON API that is a lot more elegant, scalable and maintainable. Please try to be more specific because I can’t understand what you need to do with that..

      • Hi Gianluca,

        I’m installing my node.js on ubuntu server 12.04 inside virtual machine using parallel desktop on my mountain lion.

        i’m using static ip in my ubuntu VM. My question is, when i change the example.xml why there is nothing happen with the browser? it’s always show “Try to change your xml data to update this content”

        Need advise please…..

  • I had the error
    Error: Text data outside of root node.

    when i tried to re-build the application myself instead of using the download.

    Found that the new version of xml2js threw the error using version 0.2.6 (same as this example fixed the problem).

    “name”: “mysql_test”,
    “version”: “0.0.1”,
    “private”: true,
    “scripts”: {
    “start”: “node app.js”
    “dependencies”: {
    “connect”: “*”,
    “”: “*”,
    “mysql”: “*”,
    “xml2js”: “0.2.6”

    npm update xml2js

  • Hi Gianlucca,
    Sorry forgot to mention… great example :)
    I learnt a lot from the way you used the jQuery in the static HTML page.

  • For some reason I can’t get it to work.

    The terminal return this:
    {{computerName}}:betty user$ node www/node/server.js
    info – started
    debug – client authorized
    info – handshake authorized Ufv6en46h5HkTehcZ63X
    debug – setting request GET /
    debug – set heartbeat interval for client Ufv6en46h5HkTehcZ63X
    debug – client authorized for
    debug – websocket writing 1::

    throw errnoException(process._errno, ‘watch’);
    Error: watch ENOTDIR
    at errnoException (fs.js:1019:11)
    at FSWatcher.start (fs.js:1051:11)
    at (fs.js:1076:11)
    at SocketNamespace. (/Users/user/webserver/betty/www/node/server.js:24:5)
    at SocketNamespace.EventEmitter.emit [as $emit] (events.js:117:20)
    at connect (/Users/user/webserver/betty/www/node/node_modules/
    at /Users/user/webserver/betty/www/node/node_modules/
    at SocketNamespace.authorize (/Users/user/webserver/betty/www/node/node_modules/
    at SocketNamespace.handlePacket (/Users/user/webserver/betty/www/node/node_modules/
    at Manager.handleClient (/Users/user/webserver/betty/www/node/node_modules/

    and the browser return this:

    Any idea why?

  • Hi Gianlucca,

    I would like to ask that is the error [Error: connect ETIMEDOUT]

  • hi man ,the notification works only one time , then no response to web browser , but updates are shown at terminal :( .

  • very good work!
    i tried to follow the video and got this

    am i the only one?

    osx 10.8.4
    [ macbookpro joshua-pro ~/projects/node/nodejs-push-notification-server ] node –version
    v0.10.17 node_modules/
    β”œβ”€β”€ base64id@0.1.0
    β”œβ”€β”€ policyfile@0.0.4
    β”œβ”€β”€ redis@0.7.3
    └── (xmlhttprequest@1.4.2, uglify-js@1.2.5, active-x-obfuscator@0.0.1, ws@0.4.29)

    xml2js@0.2.8 node_modules/xml2js
    └── sax@0.5.5

    Error: dlopen(/Users/macbookpro/projects/node/nodejs-push-notification-server/node_modules/xml2json/node_modules/node-expat/build/Release/node_expat.node, 1): no suitable image found. Did find:
    /Users/macbookpro/projects/node/nodejs-push-notification-server/node_modules/xml2json/node_modules/node-expat/build/Release/node_expat.node: unknown file type, first eight bytes: 0x7F 0x45 0x4C 0x46 0x02 0x01 0x01 0x00
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object. (/Users/macbookpro/projects/node/nodejs-push-notification-server/node_modules/xml2json/node_modules/node-expat/lib/node-expat.js:4:13)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:364:17)

    [ macbookpro joshua-pro ~/projects/node/nodejs-push-notification-server ] file /Users/macbookpro/projects/node/nodejs-push-notification-server/node_modules/xml2json/node_modules/node-expat/build/Release/node_expat.node
    /Users/macbookpro/projects/node/nodejs-push-notification-server/node_modules/xml2json/node_modules/node-expat/build/Release/node_expat.node: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, not stripped

    • sorry my bad.

      npm install xml2js
      it was
      npm install xml2json

      typo. feel stupid!

      • Hello Gianluca,

        i got this work on my local

        but after i made changes on xml file twice, it stops working.

        info – started
        debug – served static content /
        debug – client authorized
        info – handshake authorized Bho8qNJ-OhEa_D2QoGWZ
        debug – setting request GET /
        debug – set heartbeat interval for client Bho8qNJ-OhEa_D2QoGWZ
        debug – client authorized for
        debug – websocket writing 1::
        debug – websocket writing 5:::{“name”:”notification”,”args”:[“{\”test\”:{\”sample\”:\”aa bb\”}}”]}
        debug – websocket writing 5:::{“name”:”notification”,”args”:[“{\”test\”:{\”sample\”:\”aa\”}}”]}

        after few seconds

        it goes

        debug – emitting heartbeat for client Bho8qNJ-OhEa_D2QoGWZ
        debug – websocket writing 2::
        debug – set heartbeat timeout for client Bho8qNJ-OhEa_D2QoGWZ
        debug – got heartbeat packet
        debug – cleared heartbeat timeout for client Bho8qNJ-OhEa_D2QoGWZ
        debug – set heartbeat interval for client Bho8qNJ-OhEa_D2QoGWZ
        debug – emitting heartbeat for client Bho8qNJ-OhEa_D2QoGWZ

        • I got the same problem here on Ubuntu 13.10, firefox and chromium as browser. Node v0.10.15, npm 1.2.18

          After first loaded, it seems only repsond once or twice within no more than 5 secs. After 5 secs, the server would keep sending time-out:

          debug – websocket writing 2::
          debug – set heartbeat timeout for client WI5lOp8j4KyLuwvrXkrS
          debug – got heartbeat packet
          debug – cleared heartbeat timeout for client WI5lOp8j4KyLuwvrXkrS
          debug – set heartbeat interval for client WI5lOp8j4KyLuwvrXkrS

  • Hey there just wanted to give you a quick heads up.
    The text in your content seem to be running off the screen in Internet explorer.
    I’m not sure if this is a formatting issue or something to do with internet browser compatibility
    but I thought I’d post to let you know. The design and style look
    great though! Hope you get the problem resolved soon.

  • Hi there,
    nice tutorial :)
    I have only one question left.
    It is very unlikely that one would have a static xml-file (“example.xml” in this case) for the notifications, isn’t it?
    So what could I do to watch maybe “example.xml.php?id=123” which is filled with data from a database dependently on the url-parameter “id”? Is there any way to do that?


  • Hi,
    This is really a great tutorial. You are a real saver.
    I followed this tutorial and I am able to achieve the result.
    But, now I have a problem. I already have a website running on hostgator. Now I want to send push notifications to this website. How can I achieve this. I have tried running nodejs on my server and pasted the client side js on index.php page. But there is no response.
    Please help.


  • i have made an chat application using which is working perfectly on my localhost . and i have uploaded the code to my remote host but i dont know how to run node server.js for my remote host ….. can any one help me on this

  • Thanks.this is working fine but it works only upto 2 changes in example.xml,after 2nd change when I make a 3rd change in example.xml its not showing updated content on browser window until I refresh the client.html again..please guide.
    Any guidance would be greatly appreciated …

      • Please i got this error. i been working this for 4 days still failed to work your ssample. see below

        C:\wamp\www\NOTIFICATIONS>node server.js
        info – started
        debug – served static content /
        debug – client authorized
        info – handshake authorized 3jMnfh3eYmwm7SLp4VKL
        debug – setting request GET /
        debug – set heartbeat interval for client 3jMnfh3eYmwm7SLp4VKL
        debug – client authorized for
        debug – websocket writing 1::

        TypeError: Object

        Hello wodf drld!
        has no method ‘replace’
        at Object.exports.parser (C:\wamp\www\NOTIFICATIONS\node_modules\node-xml2js
        at C:\wamp\www\NOTIFICATIONS\server.js:31:27
        at fs.js:271:14
        at Object.oncomplete (fs.js:107:15)

        i have issues with the npm install xml2json so i install npm install node- xml2json. but i alway have a issue to the xmlcode.replace.

        Please help. I ouwld apreciate it very much. if you xan helpme to solve this issue ASAP.

  • hello Gianluca,

    I am getting following error while executing “node server.js” command

    info – started

    throw e; // process.nextTick error, or ‘error’ event on first tick
    Error: Cannot find module ‘../build/Release/node_expat.node’
    at Function._resolveFilename (module.js:332:11)
    at Function._load (module.js:279:25)
    at Module.require (module.js:354:17)
    at require (module.js:370:17)
    at Object. (/var/www/node/push/node_modules/xml2json/node_modules/node-expat/lib/node-expat.js:4:13)
    at Module._compile (module.js:441:26)
    at Object..js (module.js:459:10)
    at Module.load (module.js:348:32)
    at Function._load (module.js:308:12)
    at Module.require (module.js:354:17)

    could Please suggest over this.
    Thanks in advance.

  • Hi Gianluca Guarini ,

    Changes that i m making in my xml file is not getting reflected in the browser. What should be problem?

  • After changing some values in example.xml. The console in “node server.js” gave out some errors.

    Error: There are errors in your xml file: not well-formed (invalid token)
    at Object.module.exports [as to Json] (d:\nojs\node_modules\xml2json\lib\xml2json.js:185:15)
    at d:\nodejs\node_modules\server.js:31:25
    at fs.js:272:14
    at object.oncomplete (fs.js:108:15)

    Any idea please?

    • xml2json.js:185 throw new Error (‘There are errors in your xml file: ‘ + parser.getError

  • I found out there’s an issue also with the code. The “Last update field” returns “undefined” all the time. It turned out that xml2json’s parser.toJson(data) returns a String and not an Object, so json.time does not work.

    The obvious fix is to wrap some of the server.js variables with JSON methods to convert String to Object and pass the Object back to process as a String:
    var json = JSON.parse(parser.toJson(data));
    // adding the time of the last update
    json.time = new Date();
    // send the new data to the client
    socket.volatile.emit(‘notification’, JSON.stringify(json));

    Otherwise, thanks for the nice example code.

  • I want to change data in mysql database and get notified for that change by server itself. Is it possible? If yes, then how?

  • HI ,

    I am using this server .But unable to connect on port 443.
    My Requirement is to make server with ssl running on port 443.
    Please suggest .

  • Using the latest code from GitHub, it seemed that server.js only pushes the first change to the xml file. .. I’m new at this,but it seems you set up as if it was fs.watchFile(..) .. changing back tofs.wathFile all seems to work.

    Thanks for the time you’ve spent on this..


    btw, molto tempo fa, ho vissuto a Napoli – ancora pensare ad esso come a casa

  • HI bro, I really interest in and appreciate for your works. I have read posts on your blog, at this post I understand the scenario is to broadcast the result of the database query after a constant interval. At the previous post, you watch the example.xml file and send data when the file is changed. I would like to ask whether we can create the scenario that “watch” the Mysql database and “only broadcast” the new data, which is added to a table, or at least “only broadcast” the data when there are changes in database.


  • Thanks for the notes and code.. it’s got me started..

    Could you help with how to .emit the ??.xml on each new connection or reconnection?

    Android browsers l works as expected, except when they are in the background, no data is updated. If the page is manually refreshed, the original served page is displayed. I guess one could use javascript to modify ‘client.html’ with current data when it changes so when loaded it would be current. but .emit(‘notification’).. seems the most straight forward.

    ..thanks .. jay

  • Wow. Excellent example!!!

    It works well !!

    Bou I have one question.

    I’d like to insert PHP-codes to “client.html” just like “echo, include. str_replase etc..”.

    But it do not work.

    If I connect to “” , PHP-codes work well without nodejs not working.

    If I connect to, nodejs works well, BOU PHP-code not works…

    Please help me how to do solve this problem…

    Best regards.

  • Hi Gianluca. I’m Italian too. I’d like to use something like the code you wrote to dispatch some messages to clients connected BUT I’d like to be able to select one or more client to send the message to.
    Since I am new to node.js technology can you advice me on where to start with?

    Thanks for your help!


  • Hi…

    I can call nodejs server externally…
    Works fine using curl and localhost:

    root@server:~/www/nodejs# curl http://localhost:8080

    Push notification server

    …. …. ….

    But when calling it externally from browser or curl i get no response..

    root@server:~/www/nodejs# curl

    (no response)..

    Could you please help me? What am i doing wrong?

  • for those wondering why it doesn’t work on another machine using the IP address instead of localhost, I found out that if you edit Client.html and change the line

    var socket = io.connect(‘http://localhost:8000’);


    var socket = io.connect();

    it works!!!

  • Others are having success while here I am not even getting past the first instruction:
    $ npm install

    Sad life.

        • I think he could be. Cause that question was rather stupid and reflected that you didn’t even research before you asked it. I think i know the answer to your question already, but i ain’t spoon feeding it to you. Be a responsible developer.

  • Hello! Nice stuff, really!
    Is it a client-side feature or all this provides by server?

Leave a Reply

Your email address will not be published. Required fields are marked *