Home > Net >  data is not getting stored in my userdata.json file, it remains [ ] even if i create the file manual
data is not getting stored in my userdata.json file, it remains [ ] even if i create the file manual

Time:11-23

This is the section that contains the code for the above.

console.log is logging the data properly before the writeFile operation.

const fs = require('fs');
    const path = require('path');
    
    const p = path.join(
        path.dirname(require.main.filename),
        'data',
        'userdata.json'
    );
    
    module.exports=class userdata{
        constructor(username,phoneNo,mothersName,fathersName,address){
            this.username=username
            this.phoneNo=phoneNo
            this.fathersName=fathersName
            this.mothersName=mothersName
            this.address=address
        }
        save() {
            
            this.id = Math.random().toString();
            fs.readFile(p,(err,data)=>{
                let userData = []
                if(!err){
                    userData=JSON.parse(data)
                    console.log(userData)
    
                }
                userData.push(this)
                
                console.log("pushed")
            })
            
            fs.writeFile(p, JSON.stringify(userData),(err)=>{
                if(err){
                console.log(err)
               }
              })
            }
    

please ignore this fetchAll function

static fetchAll(){
        fs.readFile(p,(err,data)=>{
            if(err)
            return []
            return JSON.parse(data)
        }
        )
        
    }
}

Reference from NodeJS - The Complete Guide (MVC, REST APIs, GraphQL, Deno) by Maximilian Schwarzmüller udemy.

CodePudding user response:

fs.readFile is asynchronous, but you execute fs.writeFile synchronously, without waiting for the fs.readFile to complete. Put the fs.writeFile command into the callback for fs.readFile:

fs.readFile(p,(err,data)=>{
  let userData = []
  if(!err){
    userData=JSON.parse(data)
    console.log(userData)
    return
  }
  userData.push(this)
  console.log("pushed")
  fs.writeFile(p, JSON.stringify(userData),(err)=>{...})
})
  • Related