Reputation: 129
I need to store an array of URLs associated with number in json file. This is what I got so far:
json[message.guild.id] = {
songs: []
};
fs.readFile("./settings.json", "utf8", (err, data) => {
if (err) {
throw err;
} else {
json[message.guild.id] = JSON.parse(data);
}
});
json[message.guild.id].songs.push(url); // adding a new URL
fs.writeFile("./settings.json", JSON.stringify(json, null, 4), err => {
if (err) throw err;
});
And this does work, but if I try to save next URL it just overrides the existing one. What is wrong and how I can remove one of the saved URLs?
Upvotes: 0
Views: 1753
Reputation: 3230
Update 2
My first attempt overlooked the JSON issue, which I've left for posterity but you should not do because it will create an incorrect JSON object here.
However, I'm curious how you're kicking off this script. If it's the same block as you provided, you might be resetting the array for the message.guild.id
every time. You could try protecting against it with something like this:
if(!json.hasOwnProperty[message.guild.id]){
json[message.guild.id] = {};
} else if (!json[message.guild.id].hasOwnProperty('songs')){
json[message.guild.id].songs = [];
}
Again this is just an assumption since we don't see the implementation.
Update fixed typos from paste
You need to add an options object to the writeFile
method and set the flag
key to 'a'. This tells writeFile
to write in append mode. Documentation here and here.
json[message.guild.id] = {
songs: []
};
fs.readFile("./settings.json", (err, data) => {
if (err) {
throw err;
} else {
json[message.guild.id] = JSON.parse(data);
}
});
json[message.guild.id].songs.push(url); // adding a new URL
fs.writeFile("./settings.json", {encoding:"utf8", flag:'a'}, JSON.stringify(json, null, 4), err => {
if (err) throw err;
});
Upvotes: 1
Reputation: 2805
You are using callback functions, so you can't use it like that
json[message.guild.id] = {
songs: []
};
fs.readFile("./settings.json", "utf8", (err, data) => {
if (err) {
throw err;
} else {
json[message.guild.id] = JSON.parse(data);
json[message.guild.id].songs.push(url); // adding a new URL
fs.writeFile("./settings.json", JSON.stringify(json, null, 4), err => {
if (err) throw err;
});
}
});
This should work however it seems to not make sense.
Take a look at async functions, callbacks and promises. Specially how callback works, your code has to be executed inside each function
Upvotes: 0