24

In an Elixir project, you can use

Path.expand

to define a file or directory as a relative path from the current file.

For example: Path.expand("../../../lib/file.ex")

but how about finding a path from the root level of the project?

1
  • Some others visiting here might find the following useful: :code.priv_dir or :code.lib_dir. Commented Jan 19, 2023 at 12:43

2 Answers 2

32

If you'd like to get the project's root directory, use

File.cwd!

source: https://groups.google.com/d/topic/elixir-lang-talk/Ls0eJDdMMW8

(note: I pulled this here only so it's not buried in a dead forum behind Google auth wall & subject to Google data preservation policies)

Sign up to request clarification or add additional context in comments.

4 Comments

Actually, cwd this is not the project's root directory. This is the current working directory (which might be different)
@Motine did you read the forum discussion? Jose states, "if the project is being compiled with Mix, "File.cwd!" will always point to the root directory because Mix always runs from root."
Yep. But I actually did not use mix.
I'm working on an umbrella project. I'm using a module from another app in the umbrella; a call to File.cwd! in the dependency app returns the root of the running app, not the root of the dependency app.
5

In case of an umbrella app, you can create a key in your config.exs file :

config :some_app,
  project_root: File.cwd!

And then use that value from wherever you want in your project :

project_root = Application.fetch_env!(:some_app, :project_root)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.