简体   繁体   中英

Javascript/Node.js - Check if file has changed

I am coding an Ace Editor and want to check if the file that is currently opened has changed its content from another user/program etc., and then get a popup like you know it from other editors like Geany.

The code in Javascript to check if a File changed looks like this:

const fs = require("fs");

fs.watchFile("app/app.js" ,function() {
    console.log("File changed!");
});

If I make a change to the app.js file and save it, it always works the first time and shows "File changed," in the log. but when I make other changes and save the file again it sometimes shows nothing or only hugely time-delayed. I have no idea what is going on? Does somebody of you know what to change to make it reliable?

The inefficiency make be solved by using a differnt Node API.

Note the following disclaimer from the Node official docs

https://nodejs.org/docs/latest/api/fs.html#fs_fs_watchfile_filename_options_listener Using fs.watch() is more efficient than fs.watchFile and fs.unwatchFile. fs.watch should be used instead of fs.watchFile and fs.unwatchFile when possible.

Instead of fs.watchFile , use fs.watch instead, like this:

onst fs = require("fs");
fs.watch("app/app.js", function() {
    console.log("File changed!");
});

Note that the arguments for the callback functions differ:

https://nodejs.org/docs/latest/api/fs.html#fs_fs_watchfile_filename_options_listener The listener gets two arguments the current stat object and the previous stat object:

versus

https://nodejs.org/docs/latest/api/fs.html#fs_filename_argument The listener callback gets two arguments (eventType, filename). eventType is either 'rename' or 'change', and filename is the name of the file which triggered the event. Providing filename argument in the callback is only supported on Linux, macOS, Windows, and AIX. Even on supported platforms, filename is not always guaranteed to be provided. Therefore, don't assume that filename argument is always provided in the callback, and have some fallback logic if it is null.

You do not appear to be making use of any information in your example above, but if you do, make note of the above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM