Zip file into specific directory

I want to create a zip in particular location consider “/tmp/zip”.
I got two solutions for doing that,
1). One is changing File.cwd!/ to that specific folder and after creating the zip. Have to revert back to the old path

def create_zip(path) do
  old_path = File.cwd!! path
  :zip.create("", ['images'], [{:cwd, path}])! old_path

I got above reference from here → Elixir: Export, Download, Zip, and Email | by Jebin | Medium
But, i think what happen if error occurs after changing the first!. I tried to simulate the scenario in my local. The whole project path was changing, so the next APIs are not working. And doing this in distributed system is right?

2). Create a zip file in current CWD then move the zip into required folder. In my case it “/tmp/zip/”. But, i was creating and moving the file to specific directory. Is it costly operation in the API? And also, creating the zip in current project directory instead of particular directory is correct approach?

Is there is any other way to create the zip in specific directory or which method can i follow from the above?

The linked article says:

The zip creation interface is not that flexible. It doesn’t take a source directory and create a zip in a given destination directory.

But experimenting locally with Elixir 1.11 / OTP 23 it doesn’t seem like that’s true now:

# assume a directory named "crud" exists in the working directory
iex(3)>'crud/', ['mix.exs'])
{:ok, 'crud/'}

Maybe this changed in OTP since 2018?

1 Like

Why are you not using absolute paths for the output

iex(1)> :zip.create("/tmp/", ['/Users/evadne/emoji.pdf'])
{:ok, "/tmp/"}
zipinfo /tmp/ 
Archive:  /tmp/
Zip file size: 54982 bytes, number of entries: 1
-rw----     2.0 fat    65725 b- defN 21-Mar-12 00:55 /Users/evadne/emoji.pdf
1 file, 65725 bytes uncompressed, 54838 bytes compressed:  16.6%
1 Like