You can access the main module that node started with require.main from 
every module running in the same process, i.e both main module itself and 
all imported modules.

main.js:

module.touchable = "ouch!";

mdl = require('./module.js');

mdl.try_touching();

module.js:

module.exports.try_touching = function () {
    console.log(require.main.touchable);
}

Be careful that require.main is the module object, not module's globals. 
So, instead of var var_name='var_value', we used module.var_name='var_value'. 
In addition to this, instead of attaching your variables directly to module 
object itself like I did in the example above, it is better practice to use 
module.exports for reasons like consistency, niceness, and also preventing 
namespace pollution.


On Tuesday, July 3, 2012 5:47:58 PM UTC-4, josh wrote:
>
> I have a variable in server.js. how to access it from within a function 
> that is exported from a module? 
> I use mapletree as my routes library that provide me define function -
>
> var usersCollections = {};
> router.define( '/user', require('./routes/user.js') 
>
> //routes/user.js
>
> module.exports = user;
>
> function user (req, res) {
>   console.log('collection', usersCollection); // not defined
>   return res.end();
> };
>
> http://pastebin.com/SLHM85Xt
>
> here is the complete project - 
> https://github.com/oren/Y-U-NO-BIG
>

-- 
Job Board: http://jobs.nodejs.org/
Posting guidelines: 
https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines
You received this message because you are subscribed to the Google
Groups "nodejs" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/nodejs?hl=en?hl=en

Reply via email to