node.js连接并监听json url

时间:2013-08-01 18:04:41

标签: node.js sockets socket.io

任何人都可以帮我吗?

我正在尝试从json文件“example.json”获取数据 并在任何更新的情况下继续收听文件...

但是,出于某种原因,我无法让它发挥作用......

任何想法/帮助?

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 );
});

1 个答案:

答案 0 :(得分:0)

没关系,我让它上班......

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);
        });
    });
});