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
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:
WaitForSingleObject
- wait for something to change in the directory you are watching.- Send change notification to the main thread if necessary.
FindNextChangeNotification
And you should call FindCloseChangeNotification
once you are done watching.
I may be wrong, but I'm fairly certain this can't be done without some sort of polling approach (ie: check the file over some interval or just before you are about to use it).
来源:https://stackoverflow.com/questions/11495227/how-can-i-monitor-a-file-asynchronously-in-firefox