在node.js&;中从动态文件名加载JSON的最佳方式是什么;打字稿?
我正在使用node.js和Typescript创建一个简单的web应用程序,以熟悉它,我想知道加载JSON配置文件的最佳方法,该文件的文件名在运行时确定 我在网上找到了一些建议:在node.js&;中从动态文件名加载JSON的最佳方式是什么;打字稿?,node.js,json,typescript,Node.js,Json,Typescript,我正在使用node.js和Typescript创建一个简单的web应用程序,以熟悉它,我想知道加载JSON配置文件的最佳方法,该文件的文件名在运行时确定 我在网上找到了一些建议: 第一种方法似乎应该有效,但第二种方法似乎更简洁。问题是,对于第二种方法,我有以下错误: An import declaration can only be used in a namespace or module. ts(1232) 因为我想在构造函数中导入文件,并将文件名指定为参数。其次,如果我尝试将给定
An import declaration can only be used in a namespace or module. ts(1232)
因为我想在构造函数中导入文件,并将文件名指定为参数。其次,如果我尝试将给定文件名附加到要从中获取文件名的常量目录,则会出现以下错误:
';' expected. ts(1005)
下面是我试图加载JSON的类中的(非编译)代码片段,以及我试图加载的JSON文件示例
类型脚本类:
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文件?在您的示例中,
import
语句适用于TS被“编译”到JS中时,而不是在运行时使用newbuilding()
(当代码实际执行时,由节点进程编译后)
选项1是一个很好的方法来处理Node。我想您正试图摆脱笨拙的fs函数
另一种选择是使用从代码到自身的GET请求,尽管表面上是相同的,但您可以轻松地探索稍微整洁的async/await
函数*
*(上一次在几个月前,我使用了fs,我确实尝试过,但无法使用async/Wait,但现在可能已经改变了吗?感谢您的建议。我最终决定将fs与JSON.parse一起使用,这并不像我最初认为的那样尴尬。谢谢!
{
"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"
}
]
}
}