read

const fs = require('fs');

// Read synchronously
const data = fs.readFileSync('./package.json');
console.log('data', data);
console.log('data2', data.toString());


// Read asynchronously
const data2 = fs.readFile('./package.json'.function (err, data) {
    console.log('asynchronous data', data);
    console.log('asynchronous data2', data.toString());
});

// Use promise, the first way
// Async function promisesize
// function promisify(fn) {
// return function () {
// let args = Array.prototype.slice.call(arguments);
// return new Promise(function (resolve, reject) {
// args.push(function (err, result) {
// if (err) reject(err);
// else resolve(result);
/ /});
// fn.apply(null, args);
/ /});
/ /}
// }
// var readFile = promisify(fs.readFile);
// readFile('./package.json').then((res)=>{
// console.log(res.toString())
// })

// v > 8, second way
const {
    promisify
} = require('util');

var readFile = promisify(fs.readFile);
// readFile('./package.json').then((res)=>{
// console.log(res.toString())
// });
(async() = > {// var data3 = await fs.readFile('./package.json'); // Yes, no, you need a Promise object,
    var data3 = await readFile('./package.json');
    console.log('ppp', data3)
})();
// v> 10

const {readFile} = require('fs').promises;

readFile('./package.json').then((res) = >{
    console.log(res.toString())
});
Copy the code

write

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) = > {
    // May be empty file, set to empty object
    const json = data ? JSON.parse(data) : {};
    json[key] = value; / / set the value
    // Write the file again
    fs.writeFile("./db.json".JSON.stringify(json), err= > {
      if (err) {
        console.log(err);
      }
      console.log("Write successful!");
    });
  });
}

// The command line interface part
// The require('readline') module provides an interface for reading data from a readable stream such as process.stdin,
// Read one line at a time. It can be used in the following ways:
const readline = require("readline");
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  prompt: 'Please enter >'
});
rl.prompt();
rl.on("line".function(input) {
  // get name 
  // set name kkkkkk
  // nm
  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('No such operation'); }});// Close the readline.Interface instance and revoke control of the input and output streams
rl.on("close".function() {
  console.log("End of program");
  process.exit(0);
});
Copy the code