user1725316
user1725316

Reputation:

One file watch for all socket.io connection

I have an application that watch for a file changes. Once the file changed, an event is emitted to all socket.io client. Here is the code:

io.sockets.on('connection', function(socket) {
    fs.watchFile('./file.txt', {persistent:true}, function(data) {
        socket.emit('server', {message: 'File changed'});
    });
});

My question is, is it true that the code above will run file watch process as many as socket.io client connections?

Thank you.

Upvotes: 1

Views: 2961

Answers (1)

Gntem
Gntem

Reputation: 7165

yes your code will run a fs.watchFile() everytime a client connects to server, instead you could try.

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' });
  },
)

Upvotes: 5

Related Questions