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!
  File.cd! path
  :zip.create("images.zip", ['images'], [{:cwd, path}])
  File.cd! old_path
  path<>"/images.zip"
end

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 File.cd!. 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)> :zip.zip('crud/foo.zip', ['mix.exs'])
{:ok, 'crud/foo.zip'}

Maybe this changed in OTP since 2018?

1 Like

Why are you not using absolute paths for the output

iex(1)> :zip.create("/tmp/images.zip", ['/Users/evadne/emoji.pdf'])
{:ok, "/tmp/images.zip"}
zipinfo /tmp/images.zip 
Archive:  /tmp/images.zip
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