Alex Rivera | Logout

How to require a file in node.js and pass an argument in the request method, but not to the module?

Asked 2012-01-12T11:15:57.577
26

I have a module.js that must be loaded; In order to work needs objectX;

How do I pass the objectX to the module.js in the require method provided by node.js?

thanks

// my module.js
objectX.add('abc');
// error: objectX is undefined

I would like a way to do it, without having to change all my classes because would take a lot of time... and they way it is has good performance for the client side. (I mix clientfiles with serverfiles***)

Edit
Report

1 Answer

16

You can avoid changing the actual exported object by chaining in an "init" method (name it whatever you want).

Module TestModule.js:

var x = 0; // Some private module data

exports.init = function(nx) {
    x = nx; // Initialize the data
    return exports;
};

exports.sayHi = function() {
    console.log("HELLO THERE "+x);
};

And then requiring it like this:

var TM = require('./TestModule.js').init(20);
TM.sayHi();
answered 2013-05-24T19:17:20.690

Your Answer