Close #1281 Make require a public member of module

Reviewed by @felixge
v0.7.4-release
isaacs 2011-07-14 13:55:51 -07:00
parent 876712a074
commit 9b5098f509
7 changed files with 33 additions and 1 deletions

View File

@ -172,6 +172,17 @@ y.js:
console.log(x.a);
### module.require
The `module.require` method provides a way to load a module as if
`require()` was called from the original module.
Note that in order to do this, you must get a reference to the `module`
object. Since `require()` returns the `exports`, and the `module` is
typically *only* available within a specific module's code, it must be
explicitly exported in order to be used.
### All Together...
To get the exact filename that will be loaded when `require()` is called, use

View File

@ -336,6 +336,11 @@ Module.prototype.load = function(filename) {
};
Module.prototype.require = function(path) {
return Module._load(path, this);
};
// Returns exception if any
Module.prototype._compile = function(content, filename) {
var self = this;
@ -343,7 +348,7 @@ Module.prototype._compile = function(content, filename) {
content = content.replace(/^\#\!.*/, '');
function require(path) {
return Module._load(path, self);
return self.require(path);
}
require.resolve = function(request) {

View File

@ -0,0 +1,2 @@
exports.loaded = require('target');
exports.module = module;

View File

@ -0,0 +1 @@
exports.loaded = 'from child';

View File

@ -0,0 +1,5 @@
var child = require('../child');
//console.log(child.module.require, child.module);
console.log(child.module.require('target'));
console.log(child.loaded);
exports.loaded = child.module.require('target');

View File

@ -0,0 +1 @@
exports.loaded = 'from parent';

View File

@ -207,6 +207,13 @@ var amdExtraArgs = require(amdFolder + '/extra-args.js');
assert.equal(amdExtraArgs.ok, amdreg.ok, 'amd extra args failed');
// make sure that module.require() is the same as
// doing require() inside of that module.
var parent = require('../fixtures/module-require/parent/');
var child = require('../fixtures/module-require/child/');
assert.equal(child.loaded, parent.loaded);
process.addListener('exit', function() {
assert.ok(common.indirectInstanceOf(a.A, Function));
assert.equal('A done', a.A());