Вопрос

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.

Это было полезно?

Решение

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top