在node.js和Typescript中,从动态文件名加载JSON的最佳方法是什么?

4
我正在使用Node.js和TypeScript创建一个简单的Web应用程序,以增加对它的熟悉度,我想知道在运行时确定文件名的情况下加载JSON配置文件的最佳方法。
我在网上找到了一些建议: 第一种方法似乎可以工作,但第二种方法看起来更整洁。问题是,第二种方法会出现以下错误:
An import declaration can only be used in a namespace or module. ts(1232)

因为我想在构造函数中导入文件,并将文件名指定为参数。其次,如果我尝试将给定的文件名附加到我想要获取它的常量目录,则会出现以下错误:
';' expected. ts(1005)

这是我正在尝试加载JSON的类中的一段(无法编译的)代码片段,以及我正在尝试加载的示例JSON文件。
TypeScript类:
import Floor from './Floor'
import Elevator from './Elevator'
import Person from './Person'

class Building {

    public name: string
    private floors: Floor[]
    private elevators: Elevator[]
    private people: Person[]
    private time: number

    constructor(config_filename: string) {
        import * as config from '../config/'+config_filename
        const building = (<any>config).building
        this.name = name
        this.floors = []
        building.floors.forEach((floor) => {
            this.floors.push(new Floor(floor.number, floor.name))
        })
        this.elevators = []
        building.elevators.forEach((elevator) => {
            this.elevators.push(new Elevator(elevator.name, elevator.weight_capacity, elevator.start_floor_no, this))
        })
        this.people = []
        building.people.forEach((person) => {
            const person_instance = new Person(person.name, 10, person.algorithm)
            this.people.push(person_instance)
            this.floors[person.start_floor_no].addOccupant(person_instance)
        })
        this.time = 0
    }
...

示例JSON配置文件:

{
    "building": {
        "name": "Basic Inc.",
        "floors": [
            {
                "number": 0,
                "name": "Ground Floor"
            },
            {
                "number": 1,
                "name": "1st Floor"
            }
        ],
        "elevators": [
            {
                "name": "Bruce",
                "weight_capacity": 100,
                "start_floor_no": 0
            }
        ],
        "people": [
            {
                "name": "Wendy Fox",
                "start_floor_no": 0,
                "algorithm": "desk"
            }
        ]
    }
}

我应该坚持第一种方法,还是有更简洁的方式来加载仅在运行时已知文件名的JSON文件?

1个回答

2
在你的例子中,import语句适用于将TS“编译”为JS时,而不是在运行时使用new Building(<name>)(当代码实际执行时,在Node进程进行编译之后)。对于Node来说,选项1是一个不错的方法。我想你试图摆脱笨拙的fs函数。另一种选择是从代码本身使用GET请求,虽然表面上看起来相同,但可以轻松地探索一下更整洁的async/await函数。 (几个月前我最后一次尝试使用fs时,我确实尝试过但未能使其与async/await配合使用,但现在可能已经改变了?)

谢谢您的建议。最终我决定使用fs和JSON.parse,这并不像我最初想象的那么尴尬。谢谢! - Rob Streeting

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接