Home > Net >  Only write to file if data doesn't exist?
Only write to file if data doesn't exist?

Time:12-05

I am creating a push notification server, and I am storing subscriptions in a JSON file, called clients.json. This is working just fine, and I am able to use fs.writeFile('clients.json', data, callback), which is working. The problem I am having is that if there are multiple instances of a subscription in the JSON file, the server sends a push event multiple times, for every instance of the subscription.

What I am trying now is to only write the subscription object to the file if it does not already exist in the file. I have tried the following:

if (!JSON.parse(fs.readFileSync('clients.json')).endpoints.includes(subscription)) {
    clients.endpoints.push(subscription);
    fs.writeFile('clients.json', JSON.stringify(clients), err=>{if(err){console.log(err)}});
}

Seems correct to me, but it doesn't seem to care about my condition, as the code block runs every time and the subscription is inserted to the file many times.
If it helps, this is clients.json:

{
    "endpoints":[
        /* Client subscriptions end up in this array */
    ]
}

Any help would be greatly appreciated.

CodePudding user response:

In js only primitive types are compared by their values. If subscription is an object of any kind, it will return false when compared with another object, even when it contains the same data, because they are compared by object they reference.

  • Related