1

Is it possible to get a reference to a module's context object from inside that module itself? Not the global object or the exports object, but the private context object of a module...

For example inside a Node.js module I'm looking for a way to do this:

var a = 1;
var b = 2;

// CONTEXT is the reference I'm looking for
console.log(CONTEXT); // -> {a: 1, b: 2}
lrsjng
  • 2,615
  • 1
  • 19
  • 23

1 Answers1

2

The context of a module (vars, module and exports) available in a module. So if I do this in a module and require it from another script:

var _pv = 1;

var _foo = function() {
    console.log('foo');
}
exports.foo = _foo;

console.log('pv: ' + _pv);
_foo();

console.log(module);
console.log(module.exports);

It outputs:

pv: 1
foo
{ id: '/Users/bryanmac/Testing/test2/mod.js',
  exports: { foo: [Function] },
  parent: 
   { id: '.',
     exports: {},
     parent: null,
     filename: '/Users/bryanmac/Testing/test2/test.js',
     loaded: false,
     children: [ [Circular] ],
     paths: 
      [ '/Users/bryanmac/Testing/test2/node_modules',
        '/Users/bryanmac/Testing/node_modules',
        '/Users/bryanmac/node_modules',
        '/Users/node_modules',
        '/node_modules' ] },
  filename: '/Users/bryanmac/Testing/test2/mod.js',
  loaded: false,
  children: [],
  paths: 
   [ '/Users/bryanmac/Testing/test2/node_modules',
     '/Users/bryanmac/Testing/node_modules',
     '/Users/bryanmac/node_modules',
     '/Users/node_modules',
     '/node_modules' ] }
{ foo: [Function] }

Edit:

You clarified it's vars in the current scope. I don't believe you can get to the variables technically. See: Getting All Variables In Scope

But you can export those variable and then they are available on module and module.exports as I pointed out above.

Community
  • 1
  • 1
bryanmac
  • 38,941
  • 11
  • 91
  • 99