Reputation: 3
I currently have this code that get information from an API and uses gathered information and write it to a JSON file.
var xp;
fs.readFile('./xp.json', 'utf8', (err, data ) => {
if (err) throw err;
xp = JSON.parse(data);
});
console.log(m['id'] + " " + m['channel_id'] + " " + m['username']);
var usr = m['id'];
if (!xp[usr])
xp[usr] = {xpp: 0};
xp[usr].xpp++;
fs.writeFile("./xp.json", JSON.stringify(xp), (err) => {
if (err) console.error(err);
});
When I run this I get this error message: Error MSG image
So I guess the problem is with the if (!xp[usr]) xp[usr] = {xpp: 0};
My intentions with that line is:
if it's no field in the json object called usr
...
make a field looking like this:
string of usr = {
xpp = 0
}
I have been stuck on this one for some hours now. Any suggestions?
full function:
var infoUrl = "https:widget.json";
function giveXP(xyz) {
console.log("Interval Started");
request(xyz, function(error, response, body){
if(!error && response.statusCode == 200){
var parsedData = JSON.parse(body);
var memberz = parsedData['members'];
memberz.forEach(function(m){
if(m['channel_id']){
var xp;
fs.readFile('./xp.json', 'utf8', (err, data ) => {
if (err) throw err;
xp = JSON.parse(data);
console.log(m['id'] + " " + m['channel_id'] + " " + m['username']);
var usr = m['id'];
if (!xp[usr]) xp[usr] = {xpp: 0};
xp[usr].xpp++;
});
fs.writeFile("./xp.json", JSON.stringify(xp), (err) => {
if (err) console.error(err);
});
}
});
}
});
} setInterval(giveXP, 3000, infoUrl);
Upvotes: 0
Views: 69
Reputation: 2849
Perhaps xp
indeed doesn't exist at that time due to the fact that readFile
is asynchronous.
So you need to move you logic in the callback:
fs.readFile('./xp.json', 'utf8', (err, data ) => {
if (err) throw err;
xp = JSON.parse(data);
if (!xp[usr]) {
xp[usr] = {xpp: 0};
}
xp[usr].xpp++;
fs.writeFile("./xp.json", JSON.stringify(xp), (err) => {
if (err) console.error(err);
});
});
Upvotes: 0
Reputation: 544
you need to access xp[usr] once the fs.read gives you result. as its async you have to put your code in its callback. please take a look of below code
var xp;
fs.readFile('./xp.json', 'utf8', (err, data ) => {
if (err) throw err;
xp = JSON.parse(data);
console.log(m['id'] + " " + m['channel_id'] + " " + m['username']);
var usr = m['id'];
if (!xp[usr]) xp[usr] = {xpp: 0};
xp[usr].xpp++;
});
fs.writeFile("./xp.json", JSON.stringify(xp), (err) => {
if (err) console.error(err);
});
// ...
Upvotes: 1