u936293
u936293

Reputation: 16264

Passing a parameter to a called module

My app.js contains:

var m1 = require("./m1");
m1.f1(...);

My m1.js contains:

var m1 = module.exports = {};
m1.f1 = function(...) { };

I would like to pass somevariable when loading m1 from app.js:

var m1 = require("./m1")(somevariable);

How can I write m1.js so that the function definition of m1.f1 can access somevariable?

Upvotes: 1

Views: 85

Answers (3)

Brendan Hall-Hern
Brendan Hall-Hern

Reputation: 11

The answer above by Ibrahim makes sense if you want to call m1 as a function. What it seems to me, though, is that your use case would be better served by using a JS class.

That way, you can import 'm1' the regular way with require('m1') and then create an instance of M1 with new m1(<whatever you want to pass in>);

Now when you want to call M1, just use m1.f1()

To support classes, your M1 should look something like:

export default class m1 {
 constructor(param1, param2) {
  this.param1 = param1;
  this.param2 = param2;
 }

 f1() {
  do whatever with params here
 }
}

The biggest benefit of this is readability. Now when someone (or you) looks at your code, they will see where this input is coming from. Otherwise, it can be hard to track down where the params are coming from. Especially as your code gets more complex.

Upvotes: 0

ibrahim mahrir
ibrahim mahrir

Reputation: 31712

If you want to be able to do this:

var m1 = require("./m1")(somevariable);            // it is equivalent to var m = require("./m1"); and then m(someVariable); so m (the exports of the module m1.js) should be a function

then module.exports in m1.js should be a function:

// m1.js:
module.exports = function(theVariable) {
    // use variable then return the following object:

    return {
        f1: function() { /* ... */ }
    };
}

So now you can use the module in app.js like this:

// app.js:
var m1 = require("./m1")(someVariable);

m1.f1(/* ... */);

module.exports is the value that will be returned by the call to require when loading the module.

Upvotes: 1

Rafael Quintela
Rafael Quintela

Reputation: 2228

// app.js
require("./m1")(somevar);

// m1.js
module.exports = function(param) {
    return "something";
}

Upvotes: 0

Related Questions