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
You can get the length of the json file based data and also can append the id in it, check below code,
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:
undefined
because there is noreturn
)You have the choice of either use a callback function for your id method (recommended because sync functions block the thread)
or:
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 fsCAUTION: 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