需要使用Socket ioparsing生活的json文件

头一回! 我是非常新的node.js和socket.io世界我有一个json文件,其中包含以下数据,例如: –

{ "football": { "id": 1, "home": "Liverpool", "away": "Chelsea", "score": "1-0", "last scorer":"Gerrard" } } 

此文件在几秒钟内实时更新。

我真正想要实现的是parsing这个JSON,并在客户端更新相同的HTML,除此之外,我想听取任何更改的JSON文件,并再次更新到HTML客户端。 我怎么能做到这一点,对不起,如果这个问题似乎足够愚蠢,但任何build议可以帮助。

(对不起,我的电脑出现了问题,很难做到这一点;在解决问题之后我会对其进行编辑,一切都停止了)

要在文件中查找更改,请尝试如下所示: 通过AJAX监视文件更改,如何? 或者使用HTML5 File API检查文件是否已更改

服务器文件:

 var EventEmitter = require('events').EventEmitter; var footballWatcher = new EventEmitter(); io.on('connection', function (client) { // //Existing Code // //Node.js Event listener: footballWatcher.on('update', function(){ io.emit('footballUpdate', footballData); }); //Code to look for a change in the file, use this in it: if(updated){ footballWatcher.emit('update'); }); 

客户端文件:

 // //Existing Code (connections, methods, emits and responses, etc.) // socket.on('football', function(footballJSONData){ //JSON interpretation }); 

我终于find了一些东西,并与一些调整和研究其他答案我终于做了一个工作代码首先简要回顾一下这个代码是否看着你的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'); }); 

客户端:

 <!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> 

sports.json文件

 { "football": { "id": 1, "home": "Liverpool", "away": "Chelsea", "score": "1-0", "last scorer":"Gerrard" } }