koa动态配置json文件

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()
})

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值