Notes to self

Creating a ZIP file in Elixir

Creating ZIP files in Elixir is easy because of Erlang’s :zip module. Here’s how to create a ZIP archive both on disk and in memory.

To make the ZIP archive, we’ll use :zip.create/3 from Erlang:

{ok, filename} = :zip.create("file.zip", files)

The function accepts only charlists for file names, so we have to convert the file names first with String.to_charlist/1:

files = files |> Enum.map(&String.to_charlist/1)

In case you want to archive all files from a given directory, you can use File.ls! to build the file names list:

files = File.ls!("/path/to/dir") |> Enum.map(&String.to_charlist/1)

{ok, filename} = :zip.create("file.zip", files, cwd: "/path/to/dir")

In this case, I am using the cwd option (as “current working directory”) to set where the file is and prevent absolute paths from being included.

If you need a temporary directory for this or for saving the final archive, you can use Temp.path!/0 and File.mkdir/1:

tmp_dir = Temp.path!()
dir = File.mkdir(tmp_dir)

Finally, :zip.create/3 has an option to create the ZIP file entirely in memory, if that’s what you need:

{:ok, {filename, bytes}} = :zip.create("file.zip", [{'file1', "file 1 content"}, {'file2',"file 2 content"}], [:memory])

Work with me

I have some availability for contract work. I can be your fractional CTO, a Ruby on Rails engineer, or consultant. Write me at strzibny@strzibny.name.

RSS