Today I explain about file reads and writes with node file system and also very important concept called CallBacks.

First of all, we need to define the path and add a file to store data

// add a data folder and inside that products.json file
const products = [];
const fs = require("fs");
const path = require("path");


const p = path.join(
  path.dirname(process.mainModule.filename),
  "data",
  "products.json"
);


Inside the model

module.exports = class Product {
  constructor(t) {
    this.title = t;
  }

  save() {
   
    fs.readFile(p, (error, fileContent) => {
      let products = [];
      if (!error) {
        products = JSON.parse(fileContent);
      }
      products.push(this); //this should refers to the class
      fs.writeFile(p, JSON.stringify(products), (err) => {
        console.log(err);
      });
      //JSON.stringify - > takes js object or array and coverts into json
    });
  }


static fetchAll() {    //Wrong Way

      fs.readFile(p, (err, fileContent) => {
        /*The return statements inside the function is belongs to
    this inner function only
          not the outer function (fetch all)
          so ultimately this returns undefined (do not return anything)
          thats why we need to get cb- callback function
         */
        if (err) {
          return [];
        }
        return JSON.parse(fileContent);
      });
    }

To fix this issue -> We add Callbacks

Callback is a function returns a function with data

static fetchAll(cb) {
    fs.readFile(p, (err, fileContent) => {
     
      if (err) {
        cb([]);
      }
      cb(JSON.parse(fileContent));
    });
  }


Inside the Controller

we have to get the product from callback

exports.getProducts = (req, res, next) => {
 
  Product.fetchAll(
//callback function
    (products) => {
    res.render("shop", {
      prods: products,
      hasProducts: products.length > 0,
      activeShop: true,
    
    });
  });
};


These callback functions can make codes more complicated. So that we will discuss new methods to get data like -> Promises (then().catch()) and async awaits