任何人都可以幫助我嗎?node.js連接並收聽json url
我試圖從一個JSON文件「example.json」 獲取數據,並保持listeing在任何更新的情況下,文件...
但是,由於某種原因,我不能讓它去工作....
任何想法/幫助?
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);
});
「*但是,由於某種原因,我可以」噸得到它的工作.... *「:更具體的東西?你會得到什麼錯誤? – Blender
當試圖記錄數據我得到這樣的東西:和「socket.on('notification'.. 。「永不開火:/ –
Darkagelink