0

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?

1 Answer 1

1

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.

2
  • would this also be efficient if I stored it in a database? the file should be no more that 10,000 characters and changes fairly rarely. Jul 20, 2018 at 13:53
  • 1
    Yes, that shouldn't be a problem.
    – Lucas S.
    Jul 20, 2018 at 14:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.