Swift Vapor:如何读取JSON文件?

Rea*_*ues 4 swift vapor

我正在使用Vapor,服务器端Swift 4框架来创建Web服务器.我有一个我想申请的迁移,它从JSON文件中读取; 但是,大多数(如果不是全部)我在这上面看到的Swift教程都表示使用Bundle,据我所知,在开发服务器端swift应用程序时这是不可用的,这意味着这样的尝试不起作用:

if let path = Bundle.main.url(forResource: "myFile", withExtension: "json") {
...
Run Code Online (Sandbox Code Playgroud)

这引出了一个问题,给定一个相对文件路径,如何使用服务器端Swift读取文件?

Rea*_*ues 11

傻我.Vapor公开一个DirectoryConfig对象,您可以从中检索应用程序的工作目录.要解析文件,它将变为:

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)
}
Run Code Online (Sandbox Code Playgroud)

  • `app.directory.workingDirectory` 可以从 Vapor 4 开始使用 (5认同)