koa动态配置外部json文件
此方式使用pkg打包后,外部路径也是正确的
const fs = require("fs");
const path = require("path");
// const configPath = path.join(process.execPath, "../", "./config.json"); //也可以
const configPath = path.join(process.cwd(), "./config.json");
let isConfigExist = fs.existsSync(configPath);
let jsonConfig = null
if (isConfigExist) {
jsonConfig = JSON.parse(fs.readFileSync(configPath, "utf8"));
}
process.env.PORT = jsonConfig.port
console.log(`服务地址:http://${jsonConfig.host}:${jsonConfig.port}`)
koa动态配置内部json文件
直接使用require()函数把json文件引进来即可,引进来可以直接用
使用接口异步读写json文件
// 切换数据库名
router.get('/change_dbname', async (ctx, next) => {
let { dbname } = ctx.request.query
let findJson = () => {
return new Promise((resolve, reject) => {
fs.writeFile('./config/dbname.json', `{"dbname": "${dbname}"}`, function (err) {
if (err) {
resolve({ code: -1, msg: '写入文件失败' + err })
}
resolve({ code: 0, msg: '写入文件成功' })
})
})
}
ctx.body = await findJson()
})
// 读取数据库名
router.get('/read_dbname', async (ctx, next) => {
let findJson = () => {
return new Promise((resolve, reject) => {
fs.readFile('./config/dbname.json', 'utf-8', function (err, data) {
if (err) {
resolve({ code: -1, msg: '查询失败' + err })
return console.error(err);
}
resolve({ code: 0, msg: '读取文件成功', data: JSON.parse(data) })
})
})
}
ctx.body = await findJson()
})