I have came across the read and write operations using fs in Node Js.
My scenario is like, I have a file having the data like ,
[
{
"Pref":"Freedom",
"ID":"5545"
},
{
"Pref":"Growth",
"ID":"8946545"
}
]
I have to replace the Pref of the element whose ID is 5545 using Node js.
How can I do it. Thanks
To do what you want, you wound need to:
fs.readFile()JSON.parse()JSON.stringify()fs.writeFile()but this is not that simple as it may look like, because you will have to:
Considering all of that you should consider using a database to store any data that changes. Some databases like Mongo, Postgres or Redis need to be run as standalone application either on the same or on a different server. Some embedded databases like SQLite don't need a standalone process and can be run directly in your application.
It's not that it is impossible to write to JSON files and then read those files as needed, but the amount of work that you'd have to do to synchronize the access to the data all without accidentally blocking the event loop in the process is much more difficult than just using any database as intended.
You have some data:
const data = [
{
"Pref":"Freedom",
"ID":"5545"
},
{
"Pref":"Growth",
"ID":"8946545"
}
]
First we need to find the element you want to change (use [0] to only select the first in case there are multiple items with ID 5545:
const objectToChange = data.filter(item => item.ID === "5545")[0]
And then change it!
objectToChange['Pref'] = "Liberty"
We can see the change reflected in the data object:
console.log(data)
// [{
// ID: "5545",
// Pref: "Liberty"
// },{
// ID: "8946545",
// Pref: "Growth"
// }]
1- Load file: let json = JSON.parse(fs.readFileSync('file.json', 'utf-8'));
2- Update content:
json = json.map(el => {
if(el.ID === "5545") {
el.Pref = "TEST";
}
return el;
});
3- Save again maybe?
fs.writeFileSync('test.json', JSON.stringify(json), 'utf-8');