servor icon indicating copy to clipboard operation
servor copied to clipboard

Wait for write to finish

Open David-Klemenc opened this issue 4 years ago • 3 comments

I have noticed then when watching large files the browser might reload before the file write is complete and show an error. One possible solution could be to check if stat.mtime is changing (doc). I think chokidar solves this in a similar way.

The problem is that fs.watch fires an event as soon as the file is changed - not when it is finished changing (in case of a longer write).

If you want I can try and make a PR?

David-Klemenc avatar Nov 17 '20 13:11 David-Klemenc

Yeh watching files natively is a nightmare (hence why chokidar exists like you say). It would be really interesting to see if we could smooth this over without any dependencies!

lukejacksonn avatar Nov 17 '20 15:11 lukejacksonn

It should not be too difficult - what I would do is add a parameter to fileWatch - basically enabling an additional step - when fs.watch fires - you can check the mtime with fs.stat and then run the check recursively inside a setTimeout - if mtime is equal to the previous value then the file is no longer changing and you can issue a callback (?)

// recursive function that checks if a file is still changing
function awaitWriteFinish(path, prev) {
    fs.stat(path, function (err, stat) {
        if (err) {
            throw err;
        }
        if (stat.mtime.getTime() === prev.mtime.getTime()) {
            // callback
        }
        else {
            setTimeout(awaitWriteFinish, delay, path, stat);
        }
    });
}

fs.stats

David-Klemenc avatar Nov 17 '20 15:11 David-Klemenc

Nice, that looks good!

lukejacksonn avatar Nov 17 '20 16:11 lukejacksonn