Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Wait for write to finish #62

Open
David-Klemenc opened this issue Nov 17, 2020 · 3 comments
Open

Wait for write to finish #62

David-Klemenc opened this issue Nov 17, 2020 · 3 comments

Comments

@David-Klemenc
Copy link

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?

@lukejacksonn
Copy link
Owner

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!

@David-Klemenc
Copy link
Author

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

@lukejacksonn
Copy link
Owner

Nice, that looks good!

David-Klemenc added a commit to David-Klemenc/servor that referenced this issue Nov 17, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants