因此,可以watchFile
使用不在您自己的域中的文件cross-domain
。例如这样的:
var app = require('http').createServer(handler),
io = require('socket.io').listen(app),
fs = require('fs'),
homeFile = __dirname + '/home',
jsonFeed = 'https://www.example.com/data';
app.listen(8080, 'mixserver.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(jsonFeed, function (curr, prev) {
var t = prev.mtime.getTime();
fs.readFile(jsonFeed, function(err, data) {
if (err) throw err;
var data = JSON.parse(data);
socket.emit('feed', data);
});
});
});