joyent/node — Issue #2511: Feature Request - Ability to know current module
Author: kruncher
Created: 2012-01-11 14:52:21+00:00
State: open

Hello guys

It would be very useful if the following functionality were added into node so that custom libraries can manipulate the `current` module when desired.

I have managed to achieve this in an experimental application with the following hack:

```javascript
// node_modules/mylib/mylib.js

// warning, nasty hack - BEGIN

var Module = module.constructor
, orig = Module.prototype.load
;

var current = null;

Module.prototype.load = function() {
current = this;
orig.apply(this, arguments);
}

exports.currentModule = function() {
return current;
}

// nasty hack - END

exports.specialDefineFunction = function(name, item) {
// simply add definition to module exports
current.exports[ name ] = item;
}
```

Example:

```javascript
// mymodule.js

var mylib = require('mylib')
;

mylib.specialDefineFunction('cool', function() {
console.log('test');
})

// another.js

var mymodule = require('mymodule')
;

mymodule.cool(); // displays "test"
```

Please excuse the crudeness of this oversimplified example. Whilst I believe that the ability to access the "current" module would have a lot of different applications, for me I am aiming to develop the following:

- node & browser compatible modules without noise (my prototype allows a very clean syntax now, will be releasing as module in future for the masses)

- easy to use utility modules to help build more complex constructs.

Could the ability to access the current module become a feature?

Cheers