zoukankan      html  css  js  c++  java
  • 持久化

    将数据保存在文件中

    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
  • 相关阅读:
    Thrift在微服务中的使用
    MySQL 必知必会
    IDEA 内使用 git
    分布式锁
    LeetCode 图
    LeetCode 位运算
    LeetCode 数组
    LeetCode 字符串
    LeetCode 哈希表
    LeetCode 栈和队列
  • 原文地址:https://www.cnblogs.com/haishen/p/11606502.html
Copyright © 2011-2022 走看看