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

node.js connect and listen to json url

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

View additional discussion.



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

Share the post

node.js connect and listen to json url

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×