需要json文件返回错误的数据

时间:2018-12-03 15:17:59

标签: javascript node.js require

我想创建一个简单的订阅系统,该系统可以在文件中添加或删除userId。我用

初始化了一个名为subscriptions.json的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只是用于获取当前用户ID的对象。

如何重现该问题:

  • unsubscribe()
  • subscribe()
  • unsubscribe()
  • unsubscribe()

文件为空。那里没有用户ID。但是在currentUserIds中调试handleSubscription时,尽管文件为空,它仍然返回[ '164630818822684683' ]

我应该改用JSON.parse(fs.readFileSync('file'))吗?我在这里没有错。

0 个答案:

没有答案