Reputation: 107
i searched stackoverflow before asking this, none really solved my issue
I'm writing a discord bot and I'm writing a way to have custom prefixes. So far, I have this for handling situations where the prefix for a guild isn't in the json file.
const prefixfile = require('./prefixes.json');
function writePrefix(guildid) {
const currentprefixes = prefixfile;
currentprefixes[guildid] = "!";
fs.writeFile('./prefixes.json', JSON.stringify(currentprefixes), output => {
console.log(output);
});
delete require.cache[require.resolve(`./prefixes.json`)];
const prefixfile = require('./prefixes.json');
}
I get the error ReferenceError: Cannot access 'prefixfile' before initialization
EDIT: I've fixed that issue and got another:
fs.writeFile('./prefixes.json', JSON.stringify(currentprefixes), output => {
console.log(output);
});
that doesn't write anything to ./prefixes.json, even though currentprefixes has data that should be written.
any ideas?
Upvotes: 0
Views: 1898
Reputation: 107
like IAmDranged said, the variable prefixfile was not declared in the function. I fixed that by not using a function and moving it all inside my if statement. My other issue was that fs.writeFile() didn't write anything - I fixed by using fs.writeFileSync().
Upvotes: 0
Reputation: 3020
Even though a variable named prefixfile
is declared outside your function, the first line of your function references the variable declared locally with same name - even though it is still not declared at that point. This happens because all the variables of your program are added to their respective lexical scopes at compile time - before any code has a chance to run.
However, since the local variable is declared with const
, trying to access it before it has actually been declared will cause the ReferenceError
that you see.
See the TDZ (Temporal Dead Zone) notes for further information on this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let#temporal_dead_zone_tdz
Upvotes: 1