Search code examples
firefoxfirefox-addonxpcom

How can I monitor a file asynchronously in Firefox?


I want to monitor a plain text file on windows machine for changes to it. Whenever external application updates the file, my add-on is supposed to read it and act accordingly.

Going through quite bit of documentation I could not find a direct facility to do this in Firefox. So I came up the following approaches.

Please suggest.

Approach 1 - In a while loop {
a) List all the files in the directory being monitored / Use nsIFile.exists()
b) If files does exist go to next step else go to sleep
c) use "nsIFile" interface and obtain the attribute "lastModifiedTime" of the file & compare it with value stored initially
d) Sleep for 1 second.
}
I intend to use NetUtil.asyncFetch() for reading this file. Roadblocks being a) bypassing security b) performance hit when called in main thread.
Though this is not asynchronous in real sense .. I can call this as .js in "ChromeWorker" Thread

Tried above approach ..
but I could not sleep .. seems there is no way to sleep .. setTimeOut() did not help me

Approach 2 -
Little far fetched, not sure if this will work :)
Open the 'nsIFile' as 'nsIInputStreamPump' if file exists


Solution

  • There is no built-in API to get notified about file changes. However, you could use js-ctypes to call OS functions directly. So on Windows you would create a ChromeWorker and call FindFirstChangeNotification function there. You would then use a loop with the following calls:

    And you should call FindCloseChangeNotification once you are done watching.