When you need to write a temporary file to disk it is common to assume a particular path exists based on the operating system the app is running on:
tmp_file = Path.join("/tmp", filename) File.write!(tmp_file)
However depending on the configuration of the app as it is deployed in production, it may not have access to the
/tmp directory. Fortunately Elixir provides a function that returns a writable path for temporary files:
dir = System.tmp_dir!() tmp_file = Path.join(dir, filename) File.write!(tmp_file)
From the docs (
Writable temporary directory. Returns a writable temporary directory. Searches for directories in the following order: 1. the directory named by the TMPDIR environment variable 2. the directory named by the TEMP environment variable 3. the directory named by the TMP environment variable 4. C:\TMP on Windows or /tmp on Unix 5. as a last resort, the current working directory Returns nil if none of the above are writable.
I prefer to use the “bang” version
System.tmp_dir! described as:
RuntimeErrorinstead of returning
nilif no temp dir is set.
On my machine it returns something like this: