Tom Kark
Tom Kark

Reputation: 31

How to modify variables from another file in node.js

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

Answers (2)

eliasbauer
eliasbauer

Reputation: 51

You can use a dictionary/map:

variables.js

let variables = {};

export { variables };

main.js

const { variables } = require('./variables.js');

variables.x = 'whatever';

Upvotes: 1

Connor
Connor

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:

increment.js

let count = 0;

module.exports = {
  get:       () => count,
  increment: () => ++count
};

main.js

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

Related Questions