Reputation: 2036
I have two discord bots(app.js and activity.js) running in Node.JS on a Ubuntu server. The problem i am facing is that when both of them are running, only the activity.js is able to modify the file. The file is users.JSON . Code of the app.js:
const Discord = require("discord.js")
var moment = require("moment")
var data_users = fs.readFileSync('/home/discord/activity_bot/users.json', 'utf-8')
var arxeio = JSON.parse(data_users)
...
for (var i in duos) {
if (arxeio[duos[i].username]) {
console.log(`before: ` + arxeio[duos[i].username])
arxeio[duos[i].username]+=15
console.log(`after: ` + arxeio[duos[i].username])
} else {
arxeio[duos[i].username]=15
}
}
fs.writeFile('/home/discord/activity_bot/users.json', JSON.stringify(arxeio, null, 2), 'utf-8', function(err) {
if (err) throw err
console.log('entered')
})
And the code for the Activity.js is:
const Discord = require("discord.js");
var fs = require('fs');
var data = fs.readFileSync('/home/discord/activity_bot/users.json', 'utf-8')
var arxeio = JSON.parse(data)
...
var kuklos = setInterval(function(done) {
client.guilds.get('323921290543235073').channels.forEach(function(kanali, kanaliID) {
if (kanali.type === 'voice' && !kanali.name.includes("AFK")) {
kanali.members.forEach(function(melos, melosID) {
let xristis = melos.user.username;
if (arxeio[xristis]) {
arxeio[xristis]++;
} else {
arxeio[xristis] = 1
}
fs.writeFile('/home/discord/activity_bot/users.json', JSON.stringify(arxeio, null, 2), 'utf-8', function(err) {
if (err) throw err
})
})
}
})
}, 60*1000);
Where, duos is a table of members. I have concluded that the problem is the fs.writeFile in the App.js because when activity.js is not running it works. When activity.js is runnning "entered" is indeed logged in the app.js but the file is not modified. Also both commands above and below the += command show it is modified but not saved in the users.Json file. Any idea what is to blame? (except for my skillz :P )
Upvotes: 0
Views: 416
Reputation: 709
I think that the problem is in your app design. You can absolutely share a file with two processes, but you'll always have concurrency problems.
For these kind of things you have to use a database that locks rows/tables.
Upvotes: 1