0

谁能帮我这个?

我正在尝试从 json 文件“example.json”中获取数据,并在有任何更新时继续监听该文件......

但是,由于某种原因,我无法让它工作......

任何想法/帮助?

服务器.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 );
});
4

1 回答 1

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);
        });
    });
});
于 2013-08-01T21:24:10.960 回答