Adam Halasz
Adam Halasz

Reputation: 58341

Node.js: Require locals

What I want

Is it possible to pass locals to a required module? For example:

// in main.js
var words = { a: 'hello', b:'world'};
require('module.js', words);

// in module.js
console.log(words.a + ' ' + words.b) // --> Hello World

I'm asking this because in PHP when you require or include, the file which includes another files inherits it's variables, which is very useful in some cases, and I would be happy if this could be done in node.js too.

What I have tried and didn't worked

 var words = { a: 'hello', b:'world'};
 require('module.js', words);

 var words = { a: 'hello', b:'world'};
 require('module.js');

Both of these gives ReferenceError: words is not defined when words is called in module.js

So is it possible at all without global variables?

Upvotes: 1

Views: 445

Answers (2)

muffel
muffel

Reputation: 7390

The question is: What do you want to achieve?

If you want to export just a static function you can use the answer from tehlulz. If you want to store an object inside the exports property and benefit from the require-caching node.js provides a (dirty) approach would be to you globals. I guess this is what you have tried.

Using JavaScript in a Web-Browser context you can use the window object to store global values. Node provides only one object that is global for all modules: the process object:

main.js

process.mysettings = { a : 5, b : 6};
var mod = require(mymod);

mymod.js

module.exports = { a : process.mysettings.a, b : process.mysettings.b, c : 7};

Alternatively if you are not interested in the exports caching you could do something like that:

main.js

var obj = require(mymod)(5,6);

mymod.js

module.exports = function(a,b){
 return { a : a, b : b, c : 7, d : function(){return "whatever";}};
};

Upvotes: 0

Menztrual
Menztrual

Reputation: 41607

What you want to do is export it with an argument so you can pass it the variable.

module.js

module.exports = function(words){
    console.log(words.a + ' ' + words.b);
};

main.js

var words = { a: 'hello', b:'world'};
// Pass the words object to module
require('module')(words);

You can also chop off the .js in the require :)

Upvotes: 2

Related Questions