Reputation: 81
I'm trying to make a queue in node js and want to delete the first JSON object in my JSON file.
I create and store users in a JSON file and then add them in the queue JSON file by reading the users.json. The problem is that when i get the user from user.json it comes as an object within an array, and i cant filter to compare the id. So how can i do this?
// helper method to read JSON FILE.
const readFile = (callback, returnJson = false, filePath = dataPath, encoding = 'utf8') => {
fs.readFile(filePath, encoding, (err, data) => {
if (err) {
throw err;
}
callback(returnJson ? JSON.parse(data) : data);
});
};
// helper method to write on JSON FILE.
const writeFile = (fileData, callback, filePath = dataPath, encoding = 'utf8') => {
fs.writeFile(filePath, fileData, encoding, (err) => {
if (err) {
throw err;
}
callback();
});
};
// thats how i try to delete first user from the queue, but it deletes the user with index 1.
app.delete('/popLine', (req, res) => {
readFile(data => {
//const userId = req.params["id"];
delete data[1]; // remove the first element from the Line.
writeFile(JSON.stringify(data, null, 2), () => {
res.status(200).send(`queue id: removed`);
});
},
true);
});
// thats how an user is stored in queue.json
"5": [
{
"name": "teresa may",
"email": "parliament",
"gender": "male",
"id": 3
}
],
Upvotes: 0
Views: 296
Reputation:
I would prefer loading the JSON file as a JSON object (if its manageable) then delete the first entry by key and then persisting the file back on the disk (over-write) periodically or instantaneously which be necessary.
You can do a require to load a JSON file as a JSON object. But note, if you do a re-require of the changed file to reload it again during runtime, it will not get you the changes you made to the file in between but the older content from last require. In that case you need to clear the item from the require cache before getting the changes.
I am assuming the file is in order of KBs.. for larger files I wouldn’t prefer this approach, rather I would figure a way out to get that file data in a NoSQL document database.
Hope this helps :)
Upvotes: 1