当前位置: 代码迷 >> 综合 >> nodejs 使用命令行工具写入、读取json文件
  详细解决方案

nodejs 使用命令行工具写入、读取json文件

热度:78   发布时间:2023-10-17 06:57:56.0
const fs = require('fs');function set(key, value) {fs.readFile('./data.json', (err, data) => {const json = data ? JSON.parse(data) : {};json[key] = value;// 重新写入文件fs.writeFile('./data.json', JSON.stringify(json), (err) => {if (err) {console.log(err);}console.log('写入成功!');})})
}function get(key) {fs.readFile('./data.json', (err, data) => {const json = JSON.parse(data);console.log(json[key]);})
}// 调用命令行工具
// set a 1
// get aconst readline = require('readline');
const rl = readline.createInterface({input: process.stdin,output: process.stdout
});rl.on('line', function (input) {console.log(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('没有该操作!')}
});