Zip a folder containing multiple files

Verified
Added by iNTERFACEWARE

How to use an external command program to zip up a folder containing multiple files

Source Code
-- follows best practice by using local functions
-- these need to be placed before the main() module
-- therefore main() is at the end of the code

local function zip(folder)
  --Opens folder and reads in all files and adds to zip
   local fld = io.popen([[ls ]]..folder..[[/]])
   local allFls = fld:read('*a')
   local fls = allFls:split('\n')

   trace(fls)
   local script = [[zip ']]..folder..[[2.zip']]
   for i=1, #fls do 
      script = script..[[ -xi ']]..folder..[[/]]..fls[i]..[[']]
   end
   
   io.popen(script..[[ -j]])   
end

local function createDirectory(folderName)
   io.popen('mkdir -p '..folderName)
 --I added a timer to ensure enough time to create folder before creating the files.
 --Iguana is just too fast sometimes for the Operating system! 
 --Test to figure out if you need to throttle at all with your setup.
   util.sleep(2000)
end

--This is just so we have files to work with.
--Your setup will be different for what files you work with.
local function createFiles(Msg, Id)
   local X = xml.parse{data=xml_template}
   X.Patient.Id[1]        = Id
 --WARNING this is just a sample your vmd may be different
   X.Patient.Lastname[1]  = Msg.PID[5][1][1][1]
   X.Patient.Firstname[1] = Msg.PID[5][1][2]
   
   local f1 = io.open(Id.."/"..Id..[[.xml]], 'w')
   f1:write(tostring(X))
   f1:close()
   
   local f2 = io.open(Id.."/"..Id..[[.txt]], 'w')
   f2:write(tostring(X))
   f2:close()
   
end

xml_template = [[###]]

function main(Msg)
 --Parse incoming message and get Patient id to use for folder and file names
   local Inbound, Name = hl7.parse{vmd='example/demo.vmd',data=Msg}
   local Id = Inbound.PID[3][1][1]:nodeValue()
   
  --Create a folder for patient in Iguana Folder
   createDirectory(Id)
   
  --Create Multiple Files; I create an xml and a txt just to show how to 
  --compress two or more files. You could use os.rename to get an image or other file
   createFiles(Inbound, Id)
   
 --zip up the folder
   zip('/Applications/iNTERFACEWARE-Iguana/'..Id)
end
Description
How to use an external command program to zip up a folder containing multiple files
Usage Details

This example shows how to zip a folder using Info zip on a Mac. You can use other utilities like winzip, 7-Zip or even Winrar on Windows.

Note: To compress or decompress a single file you can use Iguana’s built in tools for gzip or bzip2 found here.

How to use the code:

  • Paste it into a script or load the attached project zip
  • Load some HL7 messages, you can use the the attached SampleData.txt
    Note: The project already contains the sample data
  • Examine the code and annotations to see how it works
    Note: You will need to change the script generation in the “zip” function to use it on Windows