Reputation: 10428
I'm using Vapor, the server-side Swift 4 framework for creating web servers. I have a migration that I'd like to apply that reads in from a JSON file; however, most if not all Swift tutorials I see on this indicate using Bundle
, which to my knowledge, isn't available when developing server-side swift applications, which means attempts like this don't work:
if let path = Bundle.main.url(forResource: "myFile", withExtension: "json") {
...
This begs the question, given a relative file path, how can I read in a file using server-side Swift?
Upvotes: 8
Views: 3248
Reputation: 10428
Silly me. Vapor exposes a DirectoryConfig
object from which you can retrieve the working directory of the application. To parse a file, it thus becomes:
let directory = DirectoryConfig.detect()
let configDir = "Sources/App/Configuration"
do {
let data = try Data(contentsOf: URL(fileURLWithPath: directory.workDir)
.appendingPathComponent(configDir, isDirectory: true)
.appendingPathComponent("myFile.json", isDirectory: false))
// continue processing
} catch {
print(error)
}
Upvotes: 25