TypeScript配置文件模板
Configuration.controllers.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| import { readFileSync, existsSync, mkdirSync } from 'fs' import { join } from 'path'
const CONFIG_FOLDER: string = join(__dirname, '../config') const CONFIG_FILE: string = join(CONFIG_FOLDER, './basic.json')
export class ConfigurationController { public constructor() {} public Initialize(): Configuration { if (this.readConfigurationFile() === undefined) throw new Error(`Configuration file is not defined! (path: ${CONFIG_FILE})`) return this.readConfigurationFile() as Configuration } private configurationFolderExists(): boolean { if (!existsSync(CONFIG_FOLDER)) { try { mkdirSync(CONFIG_FILE) } catch (err) { throw new Error(err as string) } } return true } private configurationFileExists(): boolean { if (!this.configurationFolderExists()) throw new Error(`Configuration folder is not exists! (path: ${CONFIG_FOLDER})`) if (!existsSync(CONFIG_FILE)) throw new Error(`Configuration file is not exists. (path: ${CONFIG_FILE})`) return true } private readConfigurationFile(): Configuration | undefined { return this.configurationFileExists() ? JSON.parse(readFileSync(CONFIG_FILE).toString()) : undefined } }
export default {}
|
index.d.ts
1 2 3 4
| declare type Configuration = { port: number; host?: string; }
|