Я хочу создать простую систему подписки, которая добавляет или удаляет идентификаторы пользователя из файла.Я инициализирую файл json с именем subscriptions.json
с
[]
У меня есть две функции: подписка и отмена подписки, и я попытался создать модуль для этой функции.
const fs = require('fs');
module.exports = {
subscribe(message){
handleSubscription(message, (userId, currentUserIds) => {
// user is already registered
}, (userId, currentUserIds) => {
currentUserIds.push(userId); // add this user id
saveUserIdsToFile(currentUserIds); // write to file
// user is now registered
});
},
unsubscribe(message){
handleSubscription(message, (userId, currentUserIds) => {
const filteredUserIds = currentUserIds.filter(currentUserId => currentUserId !== userId); // remove this user id
saveUserIdsToFile(filteredUserIds); // write to file
// user got removed
}, (userId, currentUserIds) => {
// user has not been registered
});
}
};
function handleSubscription(message, userExistsAction, userExistsNotAction){
const targetUserId = message.author.id; // get the id of the current user
const currentUserIds = require('../../data/subscriptions.json'); // read all user ids from the file
if(currentUserIds.some(currentUserId => currentUserId === targetUserId)){ // does the user id exist in the json file?
userExistsAction(targetUserId, currentUserIds);
} else {
userExistsNotAction(targetUserId, currentUserIds);
}
}
function saveUserIdsToFile(userIds){
const json = JSON.stringify(userIds);
fs.writeFileSync('./data/subscriptions.json', json);
}
Важное примечание:
message
- это просто объект для получения идентификатора текущего пользователя.
Как воспроизвести проблему:
- unsubscribe ()
- subscribe ()
- unsubscribe ()
- unsubscribe ()
Файл пуст.Там нет идентификатора пользователя.Но при отладке currentUserIds
в handleSubscription
он все равно возвращает [ '164630818822684683' ]
, хотя файл пуст.
Стоит ли использовать JSON.parse(fs.readFileSync('file'))
вместо этого?Я не понимаю ошибку здесь.