In Elixir, we can use the Erlang module erl_tar
to compress a file into tar.gz
. It is straightforward to create a tar file with erl_tar
. However, there is a caveat.
Unexpected Error
Assuming that we have a file named test.md
and run the following code:
# :erl_tar.create(TarFilename, [Filename], [Options])
:erl_tar.create("tarfilename.tar.gz",
["test.md"],
[:write, :compressed])
Surprisingly, you will receive a FunctionClauseError
which stated that there are no function clause matching in :erl_tar.add/4
. (as for Elixir 1.8.1)
Solution
This is because the expected file name type in erl_tar
seems to be charlists
. It is mentioned in Elixir Official Guide that charlists
are used mostly when interfacing with Erlang where some old libraries do not accept binaries as arguments. (The double quoted “string” is UTF-8 encoded binary)
To resolve the error, we need to use the single quoted file name, 'test.md'
.
:erl_tar.create("tarfilename.tar.gz",
['test.md'],
[:write, :compressed])
That’s all. Hopefully it helps!
You can also pass in a list of tuple into the second argument in the format of [{filenameInArchive, filename or binary}]
. For more on :erl_tar.create
refer to the documentation.
Tags: elixir