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?

1 answer

  • answered 2018-12-05 21:01 Connor

    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');

    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.