node.js + express 实现 json 文件数据获取与更新
读取与修改的方法
const fs = require('fs'); // promisify 异步处理 const { promisify } = require('util'); const path = require('path'); const readFile = promisify(fs.readFile) const writeFile = promisify(fs.writeFile) // 获取 json 数据 const getFileData = async (fileName) => { const filePath = path.join(__dirname, `../json/${fileName}.json`) const data = await readFile(filePath, 'utf-8') return JSON.parse(data) } // 修改 json 数据 const setFileData = async (fileName, data) => { const filePath = path.join(__dirname, `../json/${fileName}.json`) const datas = JSON.stringify(data, null, ' ') await writeFile(filePath, datas) } module.exports = { getFileData, setFileData }
使用
const express = require('express'); const router = express.Router(); // 更新 json 数据 const { getFileData, setFileData } = require('../common') // 用户注册 router.post('/api/register', async(req, res) => { // 获取所有用户信息 const allUserInfo = await getFileData('userData') const allUserName = allUserInfo.map(user => user.userName) const { userName, password, sex } = req.body // 判断用户是否已注册 if (allUserName.includes(userName)) { res.json({ code: 200, data: null, success: false, message: '该用户已注册!' }) return } if (!password) { res.json({ code: 200, data: null, success: false, message: '请填写账号密码!' }) return } if (!sex) { res.json({ code: 200, data: null, success: false, message: '请选择性别!' }) return } allUserInfo.push(req.body) setFileData('userData', allUserInfo) res.json({ code: 200, data: null, success: true, message: '注册成功!' }) }) module.exports = router;