Page 1 of 1

Plugin LUA Temporary Files

Posted: 27 Feb 2013 21:32
by tatewise
Several Plugins use os.getenv('TEMP')..os.tmpname() to obtain a temporary file names.

The LUA 5.1 Reference Manual says:
os.tmpname ()
Returns a string with a file name that can be used for a temporary file. The file must be explicitly opened before its use and explicitly removed when no longer needed.
When possible, you may prefer to use io.tmpfile, which automatically removes the file when the program ends.
Certainly, os.getenv('TEMP')..os.tmpname() files are not auto-deleted and must be removed using Disk Cleanup on Temporary files.
But io.tmpfile does NOT allow the file extension to be defined.

This has come to light as a result of working on the Ancestors ... Census Checker and Lookup Missing Census Facts Plugins.
Can anyone suggest the best way of using temporary files that auto-delete.

ID:6791

Plugin LUA Temporary Files

Posted: 28 Feb 2013 13:00
by Jane
I am not aware of any Auto Delete support other than disk cleanup in windows.

Another option would be to give the web pages meaningful names and clean them up next time the plugin is started.

Plugin LUA Temporary Files

Posted: 28 Feb 2013 15:09
by tatewise
I came to the same conclusion.
So I use file-names such as:

os.getenv('TEMP')..os.tmpname()..string.lower(StrPlugin):gsub(' ','')..'.html'

and similarly for '.css' and '.js' and where StrPlugin is the Plugin Name.

I include os.tmpname() so if the Plugin is run several times, while browser still has old HTML open, each run uses a different file-name.

(I use lower-case because it is more HTML friendly.)

Then to delete old versions of the files:

DeleteOldFiles(os.getenv('TEMP'),string.lower(StrPlugin):gsub(' ',''))

Code: Select all

-- Delete files accessed more than 1 hour ago --
function DeleteOldFiles(strFolder,strFile)
      intTime = os.time() - 3600
      for strEntry in lfs.dir(strFolder) do
            if strEntry ~= '.' and strEntry ~= '..' then
                  strPath = strFolder..'\'..strEntry
                  local tblAttr, strError = lfs.attributes(strPath)
                  if not tblAttr then tblAttr = { mode='attrfail', error=strError } end 
                  if tblAttr.mode == 'file' and strEntry:match(strFile) then
                        if tblAttr.access < intTime then DeleteFile(strPath) end
                  end
            end
      end
end -- function DeleteOldFiles