LoginSignup
1
0

More than 5 years have passed since last update.

Vapor 3.0 でワーキングディレクトリのファイルにアクセスする

Posted at

Vapor 3.0 でワーキングディレクトリのファイルにアクセスしたい場合は DirectoryConfig struct を利用する。

例えば、Public/sources に markdown のファイルを格納しておき、プログラム中からそのファイルを利用したい場合を考える。

...
├── Public
│   └── sources
│       ├── foo.md
│       └── bar.md
...

DirectoryConfig は vapor/core で定義されている struct であり、実装はここ (2018/05/12 現在)

これを見るとわかるように、detect という静的関数を利用してオブジェクトを生成し、そのときにプロジェクトのルートディレクトリがデフォルトのパスとして workdir プロパティに設定される。

したがって、上記の Public/sources/ にあるファイルにアクセスしたい場合は以下のようにする。

let directoryConfig = DirectoryConfig.detect()
let sourceDir = URL(fileURLWithPath: "\(DirectoryConfig.detect().workDir)Public/sources")

let fm = FileManager()

guard let files = try? fm.contentsOfDirectory(at: sourceDir, includingPropertiesForKeys: nil) else {
    throw Abort(.internalServerError) // エラー
}

// ファイルに対する処理…

ちなみに、Public/ のファイルをサーブするために利用する FileMiddleware も内部的には DirectoryConfig 利用しているようだった。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0