Node.js 一个文件监视所有socket.io连接
我有一个监视文件更改的应用程序。文件更改后,将向所有socket.io客户端发出一个事件。代码如下:Node.js 一个文件监视所有socket.io连接,node.js,socket.io,Node.js,Socket.io,我有一个监视文件更改的应用程序。文件更改后,将向所有socket.io客户端发出一个事件。代码如下: io.sockets.on('connection', function(socket) { fs.watchFile('./file.txt', {persistent:true}, function(data) { socket.emit('server', {message: 'File changed'}); }); }); 我的问题是,上面的代码是否会
io.sockets.on('connection', function(socket) {
fs.watchFile('./file.txt', {persistent:true}, function(data) {
socket.emit('server', {message: 'File changed'});
});
});
我的问题是,上面的代码是否会像socket.io客户端连接一样运行文件监视进程
谢谢。是的,每次客户端连接到服务器时,您的代码都会运行一个
fs.watchFile()
,您可以尝试一下
io.sockets.on('connection',function(socket){
socket.emit('server',{message:'hello'});
});
// the code below will check for change every 100secs and emit a message to all clients of / , and inform that the file has changed
fs.watchFile('FILEPATH', {
persistent: true,
interval: 100000,
},
function(data) {
io.emit('server', { message:'FileChanged' });
},
)
是的,每次客户端连接到服务器时,您的代码都会运行
fs.watchFile()
,您可以尝试
io.sockets.on('connection',function(socket){
socket.emit('server',{message:'hello'});
});
// the code below will check for change every 100secs and emit a message to all clients of / , and inform that the file has changed
fs.watchFile('FILEPATH', {
persistent: true,
interval: 100000,
},
function(data) {
io.emit('server', { message:'FileChanged' });
},
)
谢谢你@GeoPhoenix。我的问题是,由于socket.io不提供清晰的API文档,我不知道如何获取连接事件回调外部的套接字引用。非常感谢。我想应该是io.of('/').emit(…)或io.sockets.emit(…)而不是io.of('/').sockets.emit(…)是的,谢谢你的指点谢谢@GeoPhoenix。我的问题是,由于socket.io不提供清晰的API文档,我不知道如何获取连接事件回调外部的套接字引用。非常感谢。我认为应该是io.of('/').emit(…)或io.sockets.emit(…)而不是io.of('/').sockets.emit(…)是的,谢谢你的指点