其实现原理是使用 readline 模块提供的接口将用户在命令行中输入的内容存储到某个文件里
读取文件
定义一个 get 方法读取文件内容
function get(key) {fs.readFile("./db.json", (err, data) => {if (err) {console.log(err)}// 将二进制流转换成字符串成并转成Object对象const json = JSON.parse(data.toString());console.log(json[key]);});}
设置文件
定义一个 set 方法设置文件内容
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("写入成功!");});});}
命令行内容读取
我们使用 readline 模块提供的接口来读取命令行中的内容
readline 模块提供了一个接口,用于一次一行的读取 可读流 (例如 process.stdin)中的数据。
// 命令行接口部分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'){// 退出 readlinerl.close();}else {console.log('没有该操作');}});rl.on("close", function() {console.log("程序结束");process.exit(0);});
每当 input 流接收到行尾输入(\n、 \r 或 \r\n)时就会触发 'line' 事件。 这种情况通常发生在当用户按下 <Enter> 键或 <Return> 键。因此我们通过监听 line 事件来获取用户在命令行中输入的内容。
