skip to Main Content

i wanted to create a id for my list of objects which i am storing it in a .json file(just wanted it as a dummy database which stored info), i wanted to give the id as 1,2,3,4… for each object created, for this i wanted to find the length of the array in the .json file hence i use the code shown below

var idNo = ()=>{
    fs.readFile('xyz.json','utf-8',(err,data)=>{
        if(err) throw err;
        const xyz = JSON.parse(data);
        return xyz.length + 1;
        
    });
};

edit: i have tried correcting the code and now the id is generated something like

    let idNo = ()=>{
    fs.readFile("xyz.json", "utf-8" , (err,data)=>{
        if(err) throw err;
        try{
            if(JSON.parse(data)[0] == null) return 0;
            return JSON.parse(data)[JSON.parse(data).length].id + 1;

        }
        catch(err){
            throw err;
        }

    })
}

and to then store the a new set of object i have done something like this (also the parseInt(idNo++) is done because idNo is not accepted when given to the key id)

    const newxyz = {
    id: parseInt(idNo++),
    title: req.body.title,
    description: req.body.description
  };
  fs.readFile("xyz.json",'utf-8',(err,data)=>{
    if(err) throw err;
    const todo = JSON.parse(data);
    todo.push(newxyz);
    fs.writeFile("xyz.json",JSON.stringify(newxyz),(err)=>{
        if(err) throw err;
      });
  });

2

Answers


  1. You can get the length of the json file based data and also can append the id in it, check below code,

    function Func() {
        fetch("https://dummyjson.com/products")
            .then((res) => {
            return res.json();
        })
        .then((data) => {
            console.log(data.products.length);
            console.log(data); 
        });
    }
    <!DOCTYPE html>
    <html lang="en">
        <head>
            <title>JSON data length</title>
        </head>
        <body>
            <div role="button" onclick="Func()">Click Here</div>
            <script src="script.js"></script>
        </body>
    </html>
    Login or Signup to reply.
  2. Like I hinted in the comments, you cannot return the value from the callback function like this, because the callback is a different function, the flow would be:

    • start of the main function
    • launch the async readFile
    • return from the main function (value undefined because there is no return)
    • [asynchronous operations of readFile]
    • start of the readFile callback
    • return the id to readFile, which does nothing (readFile doesn’t expect a result)

    You have the choice of either use a callback function for your id method (recommended because sync functions block the thread)

    var idNo = (callback)=>{
        fs.readFile('xyz.json','utf-8',(err,data)=>{
            if(err) throw err;
            try{
                const xyz = JSON.parse(data);
                callback(xyz.length); //or xyz.length + 1 if your ids are 1-indexed
            }catch(e){
                //invalid JSON, either throw(e); or callback(0); depending on use case (or callback(1); if 1-indexed)
            }
        });
    };
    
    idNo((id)=>{
        //do something with the id
    });
    

    or:

    var idNo = ()=>{
        var data = fs.readFileSync('xyz.json','utf-8');
        try{
            const xyz = JSON.parse(data);
            return xyz.length; //or xyz.length + 1 if your ids are 1-indexed
        }catch(e){
            //invalid JSON, either throw(e); or return 0; depending on use case (or return 1; if 1-indexed)
        }
    };
    
    var id = idNo();
    //do something with the id
    

    You also have the possibility to use the promise based API and have the best of both worlds (non thread blocking file read without having to use a callback) with await, but that would require importing fsPromise instead of fs

    CAUTION: Be careful also that if you use such custom code for ids, you will maybe run into id conflicts later (what happens when the function is called twice at the same time?). Usually databases apply different sorts of locks to prevent concurrence problems, with your code you risk to have duplicate entries problems if different instances access the file at the same moment

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search