Node.js: Creating incremental watchfile listeners on client connect and removing them respectively
Problem
I currently have a client connection event, which when fires, starts watching a file. When a second client connects, the same file is watched again. (fs.watchFile()
is used)
On the client disconnection event, the file is unwatched. (fs.unwatchFile()
is used) So if the first client disconnects, the file is also unwatched for the second client.
How do I work around this? I've tried using the Listener function of fs.watchfile
and fs.unwatchFile()
but I don't know how to name each listener differently on a client connect.
From what I know, creating a listener is done by assigning a variable like such:
var listener1 = function (curr, prev) {
console.log('touched 1');
});
Then the listener can be watched or unwatched:
fs.watchfile('data.log', listener1);
fs.unwatchFile('data.log', listener1);
How do I name that listener uniquely every time a client connects? So then I can unwatch the file by listener instead of by file?
Solution
Create an object, keyed by whatever you're using to identify clients, whose values are the individual listeners:
var listeners = {};
...
// When client connects
listeners[clientId] = function(curr, prev) {
...
};
fs.watchfile('data.log', listeners[clientId]);
...
// When client disconnects
fs.unwatchfile('data.log', listeners[clientId]);
As a general rule, if you find yourself wanting a bunch of similarly-named variables, one for each instance of something, what you really want is a data structure like an array or object.
Discussion
View additional discussion.