2

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

dpb
  • 353
  • 4
  • 15
  • In nightly, OS.File.watch landed so you can use that now. Windows only right now though. Mac and linux are in the works. – Noitidart Oct 15 '14 at 19:48

2 Answers2

4

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.

Wladimir Palant
  • 56,865
  • 12
  • 98
  • 126
  • From documentation I could make out that we can use "js-ctypes" inside a chrome worker. However one has to use "FindNextChangeNotification" & "ReadDirectoryChanges" which are C++, so I have to write shim for them first. Again since Gecko 8.0, calling XPCOM from inside ChromeWorkers is not permitted, so I will have to pass all the data read from the file to the main JS thread using listener/event object. I think this is a long way. – dpb Jul 16 '12 at 13:33
  • Nice Suggestion - Implemented it :) – dpb Sep 23 '12 at 20:22
  • @dpb i was wondering if you accomplished this in js-ctypes, it would be awesome to see! – Noitidart Apr 10 '15 at 03:32
0

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).

erikvold
  • 15,988
  • 11
  • 54
  • 98