需要使用Socket io解析实时json文件

Ash*_*nha 1 parsing json node.js socket.io

首先是一个抬头!我对node.js和socket.io的世界很新.我有一个json文件,其中包含以下数据,例如: -

{
"football": {

            "id": 1,
            "home": "Liverpool",
            "away": "Chelsea",
            "score": "1-0",
            "last scorer":"Gerrard"
             }
}
Run Code Online (Sandbox Code Playgroud)

此文件几秒钟即可实时更新.

我真正想要实现的是解析这个json并将其更新到客户端的html,除此之外我想监听json文件中的任何更改并再次更新到html客户端.我怎么能做到这一点,对不起,如果这个问题看起来很愚蠢,但任何建议都可以提供帮助.

Ash*_*nha 5

我终于找到了一些东西并进行了一些调整并研究了其他答案我终于制作了一个正常工作的代码首先简要回顾一下这个代码的作用是什么看着你的json文件(在这种情况下是sports.json)如果检测到变化那么只读取json文件(在这种情况下,sports.json)然后将读取的json文件发送到连接的客户端

在客户端,只要您对json文件进行更改,魔法就会开始

PS:有一个关于fs.watch在手动编辑和保存时两次触发的讨论(我将很快提出解决方法并在此更新)

服务器端

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var jf = require('jsonfile'); //jsonfile module
var fs = require('fs'); //require file system

app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html');
});



io.sockets.on('connection', function(socket) {
fs.watch("sports.json", function(event, fileName) { //watching my        sports.json file for any changes
    //NOTE: fs.watch returns event twice on detecting change due to reason that editors fire 2 events --- there are workarounds for this on stackoverflow

    jf.readFile('sports.json', function(err, data) { //if change detected read the sports.json 

        var data = data; //store in a var
        console.log('sent') //just for debugging
        socket.volatile.emit('notification', data); //emit to all clients
    });

});

});

http.listen(3000, function() { //listen to 3000
console.log('listening on *:3000');
});
Run Code Online (Sandbox Code Playgroud)

客户端:

<!doctype html>
<html>
  <head>
    <title>Socket.IO data</title>
<body>


<p id ="data">A data will appear here on change</p>

<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
    <script src="http://code.jquery.com/jquery-1.11.1.js"></script>
 <script>
       var socket = io.connect('http://localhost:3000'); //you can replace localhost with your public domain name too!!

    socket.on('notification', function (data) {

        $('#data').text(data.football.home); //Liverpool

    });

    </script>
</body>
Run Code Online (Sandbox Code Playgroud)

sports.json文件

{
"football": {

            "id": 1,
            "home": "Liverpool",
            "away": "Chelsea",
            "score": "1-0",
            "last scorer":"Gerrard"
             }
}
Run Code Online (Sandbox Code Playgroud)