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("", 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 |>

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

files =!("/path/to/dir") |>

{ok, filename} = :zip.create("", 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("", [{'file1', "file 1 content"}, {'file2',"file 2 content"}], [:memory])


I wrote a complete guide on web application deployment. Ruby with Puma, Python with Gunicorn, NGINX, PostgreSQL, Redis, networking, processes, systemd, backups, and all your usual suspects.

More →