node读取json文件

 

一、引入依赖包

const fs = require('fs')
const path = require('path')
const configFile = path.resolve(__dirname, './config.json')

  

二、读取文件

/**
* 读取文件
*
*/
router.get('/get_config', async ctx => {
try {
const data = fs.readFileSync(configFile, 'UTF-8').toString()
let config = JSON.parse(data)
ctx.body = config 
} catch (error) {
console.log('get_config.error', error)
}

  

三、写入文件

/**
* 写入文件
*
*/
router.post('/add_config', async ctx => {
try {
const data = ctx.request.body
fs.writeFileSync(configFile, JSON.stringify(data))
ctx.body = data 
} catch (error) {
console.log('add_config.error', error)
}
})

  

 

相关文章:

  • 2021-11-28
  • 2021-07-03
  • 2021-10-20
  • 2021-11-25
  • 2021-08-24
  • 2021-06-23
  • 2021-08-10
猜你喜欢
  • 2022-12-23
  • 2022-01-23
  • 2022-01-01
  • 2021-12-28
相关资源
相似解决方案