关于fs:使用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! ')})