Elixir中如何跨平台获取用户默认目录(如配置目录)
Elixir跨平台获取用户标准目录的主流方案
第三方库方案(首选)
Elixir生态中对应Rust dirs 库的成熟实现是Erlang生态的 :dirs 包,完全兼容各操作系统的目录规范,无需自行处理平台差异,是目前的主流选择。
安装方式
在项目的mix.exs依赖列表中添加:
defp deps do [ {:dirs, "~> 1.0"} ] end
执行mix deps.get安装即可。
常用API
直接调用对应函数即可拿到对应系统的标准目录:
- 获取用户配置目录:
:dirs.config_dir()
自动适配不同系统的默认路径:- Linux:
~/.config - macOS:
~/Library/Application Support - Windows:
C:\Users\用户名\AppData\Roaming
- Linux:
- 其他常用目录:
- 用户主目录:
:dirs.home_dir() - 文档目录:
:dirs.document_dir() - 桌面目录:
:dirs.desktop_dir() - 缓存目录:
:dirs.cache_dir()
- 用户主目录:
实际场景示例
你的配置文件读取需求可以直接这么实现:
# 替换为你的应用专属标识,避免和其他应用配置冲突 app_config_dir = Path.join(:dirs.config_dir(), "your_custom_client") port_config_path = Path.join(app_config_dir, "port") port = if File.exists?(port_config_path) do port_config_path |> File.read!() |> String.trim() |> String.to_integer() else # fallback默认端口 8080 end
原生实现方案(无第三方依赖)
如果不想引入额外依赖,可以自行判断操作系统类型读取对应路径,示例代码如下:
defmodule DirUtils do def config_dir do home = System.user_home!() case :os.type() do {:win32, _} -> System.get_env("APPDATA") || Path.join(home, ".config") {:unix, :darwin} -> Path.join(home, "Library/Application Support") {:unix, _} -> Path.join(home, ".config") end end end
该方案需要自行处理各类边缘兼容问题,适合轻量小型项目使用。
内容的提问来源于stack exchange,提问作者John C
相关产品推荐
相关产品推荐

