Search code examples
javascriptnode.jsvariablesmoduleglobal-variables

How to pass variables into NodeJS modules?


In one of my JS files I include another one. How can I set variables in the included module?

I thought doing something like this would work

var mymodule = require('mymodule.js');
mymodule.myvariable = 'test';

And then in mymodule

this.myvariable === 'test';

But this doesn't work, it's undefined. What are the various options for passing a value into a module? I could just add the variable as a parameter to every function I call in mymodule, but that isn't ideal.

Is there a way to do it without globals, so that I can set the variables independently in various required modules, like this?

var mymodule1 = require('mymodule.js');
var mymodule2 = require('mymodule.js');
mymodule1.myvariable = 'test1';
mymodule2.myvariable = 'test2';

Solution

  • NodeJS require() will always load the module once so you will need to implement scoping into your module where different instances of the module can exist with their own internal state.

    You can implement your module as a JS class like:

    var MyModule = function(){};
    
    MyModule.prototype.someFunction = function(params){
        this.someVar = params;
    }
    
    MyModule.prototype.anotherFunction = function(key, value){
        this[key] = value;
    }
    
    module.exports = MyModule;
    

    Then in your code;

    var MyModule = require('MyModule');
    
    someModule = new MyModule();
    
    // treat someModule like an object with its getters/setters/functions