Search code examples
javascriptnode.jsjsondiscorddiscord.js

TypeError: Cannot read properties of undefined (reading 'link') in json


I'm trying to send a message containing link from json file, but if I update it - the code says TypeError: Cannot read properties of undefined (reading 'link'), and it won't see this link until I restart my code!

My sources.json file:

{
    "968": {
        "link": "1"
    },
    "970": {
        "link": "2"
    },
    "971": {
        "link": "3"
    },
    "972": {
        "link": "4"
    },
    "977": {
        "link": "5"
    },
    "979": {
        "link": "6"
    }
}

The code I'm using is:

const sources = require('../folder/sources')
let source = sources[number].link

Is there any way to fix it without restarting my bot all the time?


Solution

  • The require function will always cache the module the first time running in a process as to not have to excessively use disk read resources. As such if changes are made they will not be accredited for as the require cache already exists. I've listed the two primary ways to solve this issue below using my test module ./file.js.

    Clearing the module cache:

    delete require.cache[require.resolve('./file.js')];
    const newImport = require('./file.js');
    

    Or using the fs module and parsing the data returned.

    const fs = require('fs');
    const data = fs.readFileSync('./file.js', 'utf-8');
    const dataJson = JSON.parse(data);