使用json文件在后端存储数据

码农天地 -
使用json文件在后端存储数据

使用可读取的文件,操作需要存/取的数据;

const fs = require('fs');

// 获取数据
const get = (key) => {
    // 读取文件
    fs.readFile('./db.json', (err, data) => {
        const json = JSON.parse(data);
        console.log(json[key]);
    })
}

// 存入数据
const set = (key, value) => {
    fs.readFile('./db.json', (err, data) => {
        const json = data ? JSON.parse(data) : {};
        json[key] = value;
        // 写入文件
        fs.writeFile('./db.json', JSON.stringify(json), err => {
            if (err) {
                console.log(err)
            }
            console.log('write Success!');
        })
    })
}

// 使用命令行接口方式,在控制台输入值来模拟接收到接口传入的值(如果有接口传入值,则以下的方式可以忽略)
const readline = require('readline');
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
});  // 控制输入和输出

rl.on('line', (input) => {
    const [op, key, value] = input.split(' ');
    if (op === 'get') {
        get(key)
    } else if (op === 'set') {
        set(key, value)
    } else if (op === 'quit') {
        rl.close()
    } else {
        console.log('没有操作')
    }
})

rl.on('close', () => {
    console.log('close! ')
})
特别申明:本文内容来源网络,版权归原作者所有,如有侵权请立即与我们联系(cy198701067573@163.com),我们将及时处理。

Tags 标签

加个好友,技术交流

1628738909466805.jpg