我终于找到了一些东西,经过一些调整和研究其他答案,我终于制作了一个工作代码
首先简要回顾一下这段代码的作用
观看您的 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"
}
}