node.js connect and listen to json url

Problem

Can anyone help me with this?

I'm trying to get data from a json file "example.json" and keep listeing to the file in case of any update...

but, for some reason I can't get it to work....

any idea/help?

server.js :

var app = require('http').createServer(handler),
    io = require('socket.io').listen(app),
    fs = require('fs');
app.listen(8080, 'fire.dev');

function handler(req, res) {
    fs.readFile(__dirname + '/home', function(err, data) {
        if (err) {
            res.writeHead(500);
            return res.end('Error loading home');
        }

        res.writeHead(200);
        res.end(data);
    });
}

io.sockets.on('connection', function(socket) {
    fs.watch(__dirname + '/example.json', function(data) {
        fs.readFile(__dirname + '/example.json', function(err, data) {
            if (err) throw err;

            JSON.parse(data);
            console.log('============');
            console.log(data);
        });
    });

    socket.addListener('end', function(result) {
        socket.volatile.emit('notification', result);
    });
});

html:

var socket = io.connect('fire.dev:8080');

socket.on('notification', function (data) {
    $('.j-alert').fadeIn(2000);
    document.title = document.title + ' (' + data.number + ')';
    $('.j-red-alert').html( data.number );
});
Problem courtesy of: Darkagelink

Solution

nevermind, I got it to work...

var app = require('http').createServer(handler),
    io = require('socket.io').listen(app),
    fs = require('fs'),
    homeFile = __dirname + '/home',
    jsonFile = __dirname + '/home/data';
app.listen(8080, 'test.dev');

function handler(req, res) {
    fs.readFile(homeFile, function(err, data) {
        if (err) {
            res.writeHead(500);
            return res.end('Error loading home');
        }

        res.writeHead(200);
        res.end(data);
    });
}

io.sockets.on('connection', function(socket) {
    fs.watchFile(jsonFile, function (curr, prev) {
            console.log('the current mtime is: ' + curr.mtime);
            console.log('the previous mtime was: ' + prev.mtime);


        fs.readFile(jsonFile, function(err, data) {
            if (err) throw err;

            var data = JSON.parse(data);
            socket.emit('notification', data);
        });
    });
});
Solution courtesy of: Darkagelink

Discussion

There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.