How to include static assets in an Elixir application

by Adam Davis

Table of contents:



def get_my_file_stream() do
  Application.app_dir(:my_app, "/priv/my_file.txt")

Diving deeper

If the above info solved your problem, great! You can go ahead and close this page.

But if you want to learn more about this topic, keep reading.

The legacy of OTP

The Elixir programming language is built on top of Erlang/OTP. If you don’t know about Erlang/OTP, check out this page from the Erlang FAQ.

Within Erlang/OTP applications, there is a standard directory structure, which looks like this:

─ ${application}
	├── doc
	│   ├── internal
	│   ├── examples
	│   └── src
	├── include
	├── priv
	├── src
	│   └── ${application}.app.src
	└── test

The proper directory for storing static assets in these applications is /priv, and Elixir inherits this structure.

If you’d like to see more details on Erlang/OTP applications, check out this page in the OTP Design Principles User’s Guide.

Leveraging the Erlang :code module

Although we used Application.app_dir above, that’s not the only way to get the file path.

Another approach would be to use the Erlang :code module, which you can call directly from your Elixir code (docs here).

The :code module has a function called priv_dir/1 which will return the path to the priv directory for the given application (docs here). Then, you can get the complete path for your file using Path.join/2.

def get_my_file_stream() do
  |> Path.join("my_file.txt")

Adam Davis

Share this post: