servor
servor copied to clipboard
Wait for write to finish
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?
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!
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);
}
});
}
Nice, that looks good!