Reputation: 31
I'm currently working with the discord.js
library.
I guess I can call it by this name, but whenever I want to access a file, this doesn't work.
Let's say I have a file called calc.js
and I want to access the main.js
file and take a variable out of there using exports and require it to just take the value out of it.
But I haven't found even one way online to modify the variables and return another value to the file.
Can someone help me?
Upvotes: 1
Views: 3410
Reputation: 51
You can use a dictionary/map:
let variables = {};
export { variables };
const { variables } = require('./variables.js');
variables.x = 'whatever';
Upvotes: 1
Reputation: 1855
As noted, JavaScript doesn't pass every variable by reference. If you need to access a primitive value like a number, you could declare it as a local variable and export functions to access and modify it. Something like this rough example:
let count = 0;
module.exports = {
get: () => count,
increment: () => ++count
};
const { get, increment } = require('./increment.js');
console.log(get());
console.log(increment());
console.log(get());
Edit: You should probably not name your accessor get
, as that's the key word used to describe getters in ES6. Or better yet, turn such a get
function into a getter with a more suitable name.
Upvotes: 2