将数据保存在文件中
const fs = require('fs') function get(key){ fs.readFile('./db.json', (err, data)=>{ const json = JSON.parse(data) console.log(json[key]); }) } function 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('写入成功!'); }) }) } // 命令行接口方式 const readline = require('readline') // 控制输入和输出,这里得到的是输入和输出流 const rl = readline.createInterface({ input : process.stdin, output: process.stdout }) // 监听事件:得到一个新的行的时候(输入一个新的东西的时候) rl.on('line', function(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', function(){ process.exit(0) })
在控制台 node index.js 后,输入以下内容进行测试
set a {name:'laowang'}
get a