Search code examples
node.jswatchfileupdate

Node.JS - Watching AND getting changes made to a file


How can I watch and get changes made to a file in Node.JS? I've heard that fs.watch and fs.watchFile are pretty buggy and that they should be avoided, but libraries such as node-watch and chokidar don't output the oldFile/newFile (If I'm mistaken, please let me know). So what's a way to watch and output the changes of a file?


Solution

  • You will have to manage oldFile yourself.

    Store the file data somewhere initially. When the file changes, compare it's data with the stored old data and use the diff for your application. The overwrite your stored data with the new file data and wait for the next change.

    If the file is small or changes often, you can store the file data in a variable. Otherwise it might be more memory efficient to copy the file on the file system each time.