Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File watching in Node.js

I'm writing a Node.js server that watches a directory full of empty files for changes. When a file changes, it notifies a client, then empties the file. The watch code is:

fs.watch("./files/", function(event, targetfile){
        console.log(targetfile, 'is', event)
        fs.readFile("./files/"+targetfile, 'utf8', function (err,data) {
                if (err) {
                        return console.log(err);
                }
                if (data=="") return; //This should keep it from happening
                //Updates the client here
                fs.truncate("./files/"+targetfile, 0);
        });
});

The change event happens twice, thus the client gets updated twice. This can't happen. Its like the watch function is being called twice at the same time, and both execute before either can get to the truncate command. How do I keep this from happening? I can't, say, block a thread because I need it to be responsive in real time for the other files.

Thank you for the help. I'm new to Node.js, but so far I'm loving it.

like image 941
Osmium USA Avatar asked Dec 09 '25 19:12

Osmium USA


1 Answers

You can use the underscore utility method Once that keeps the function from executing more than once. You'd have to make your code look like this:

var func = _.once(function(targetfile){
    fs.readFile("./files/"+targetfile, 'utf8', function (err,data) {
        if (err) {
                return console.log(err);
        }
        if (data=="") return; //This should keep it from happening
        //Updates the client here
        fs.truncate("./files/"+targetfile, 0);
    });
});
fs.watch("./files/", function(event, targetfile){
    console.log(targetfile, 'is', event);
    func(targetfile);
});

If you want it executed more than once, but you want to filter out duplicate events, you can use a function such as throttle or debounce.

like image 159
gcochard Avatar answered Dec 12 '25 09:12

gcochard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!