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 a
const 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('没有该操作!')
}
});
nodejs 使用命令行工具写入、读取json文件
最新推荐文章于 2024-06-23 23:09:37 发布