3

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.

2
  • 1
    The second event is being triggered by you truncating the file... Commented Dec 22, 2013 at 22:52
  • It is not because it's updating the client twice with the data. Commented Dec 22, 2013 at 23:21

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Throttle looks like what I want... I'll try it and if it works I'll accept the answer.
I was wrong. debounce is what I wanted. But it worked. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.