Я создал викторины Discord, используя Node JS, и мне не удается заставить его правильно читать текстовый файл.
Я хотел бы, чтобы он прочитал файл ПОСЛЕ того, как он был обновлен с помощью точек, но он всегда читается как пустой (из-за async / syn c природы JS, я полагаю).
Вот код для объявления победителя викторины:
finalScores = readFullText('triviaresults.txt')
receivedMessage.channel.send("The winner is " + triviaWinner + " with 5 points. Congratulations!")
//"Final scores: \n" + finalScores)
Вот код для чтения файла triviaresults.txt:
function readFullText(filename){
var data = fs.readFileSync(filename, 'utf8')
return data
}
Вот код для обновления файла triviaresults.txt с точками:
function writeToResults(user){
const fs = require('fs')
var foundName = "false"
var newText = ""
try {
//read the file into lines variable, split at new lines
var lines = require('fs').readFileSync('triviaresults.txt', 'utf-8')
.split('\n')
.filter(Boolean);
//loop through each line, checking if the user was found
lines.forEach((line) => {
if (user == line.split(':')[0]) {
//gets users current score
var oldScore = line.split(': ')[1]
//converts current score to integer for adding purposes
oldScore = parseInt(oldScore, 10)
//adds 1 to their score
var newScore = oldScore + 1
//replaces old line with new line/score
var newLine = line.replace(/.$/,newScore)
//sets foundName to true so it knows not to add the name at the bottom
foundName = "true"
newText = newText + newLine + "\n"
scoreCheck = newScore
} else {
if (newText == "") {
newText = line + "\n"
} else {
newText = newText + line + "\n"
}
}
})
if (foundName == "false") {
if (newText == "") {
newText = user + ": 1"
} else {
newText = newText + user + ": 1"
}
}
fs.writeFile('triviaresults.txt', newText, (err) => {
if (err) throw err;
})
} catch(e) {
console.log('Error:', e.stack);
}}
Я уверен, что есть простое решение, и я не могу его увидеть из-за моего ограниченного опыта работы с js.