From f86ec1366f71f33f3b39b769238076ca898fc619 Mon Sep 17 00:00:00 2001 From: isaacs Date: Wed, 2 Feb 2011 09:56:32 -0800 Subject: [PATCH] Closes GH-619 Make require.main be the main module --- lib/module.js | 11 ++++++++--- test/fixtures/not-main-module.js | 4 ++++ test/simple/test-module-loading.js | 8 ++++++++ 3 files changed, 20 insertions(+), 3 deletions(-) create mode 100644 test/fixtures/not-main-module.js diff --git a/lib/module.js b/lib/module.js index de2f7abf695..231f755b150 100644 --- a/lib/module.js +++ b/lib/module.js @@ -155,7 +155,7 @@ Module._resolveLookupPaths = function(request, parent) { }; -Module._load = function(request, parent) { +Module._load = function(request, parent, isMain) { if (parent) { debug('Module._load REQUEST ' + (request) + ' parent: ' + parent.id); } @@ -183,6 +183,12 @@ Module._load = function(request, parent) { } var module = new Module(id, parent); + + if (isMain) { + process.mainModule = module; + module.id = '.'; + } + Module._cache[filename] = module; module.load(filename); return module.exports; @@ -306,8 +312,7 @@ Module._extensions['.node'] = function(module, filename) { // bootstrap main module. Module.runMain = function() { // Load the main module--the command line argument. - process.mainModule = new Module('.'); - Module._load(process.argv[1]); + Module._load(process.argv[1], null, true); }; Module._initPaths = function() { diff --git a/test/fixtures/not-main-module.js b/test/fixtures/not-main-module.js new file mode 100644 index 00000000000..3da57f44285 --- /dev/null +++ b/test/fixtures/not-main-module.js @@ -0,0 +1,4 @@ +var assert = require('assert'); +assert.notEqual(module, require.main, 'require.main should not == module'); +assert.notEqual(module, process.mainModule, + 'process.mainModule should not === module'); diff --git a/test/simple/test-module-loading.js b/test/simple/test-module-loading.js index 25002fa6f04..d2e5308952b 100644 --- a/test/simple/test-module-loading.js +++ b/test/simple/test-module-loading.js @@ -5,6 +5,14 @@ var fs = require('fs'); common.debug('load test-module-loading.js'); +// assert that this is the main module. +assert.equal(require.main.id, '.', 'main module should have id of \'.\''); +assert.equal(require.main, module, 'require.main should === module'); +assert.equal(process.mainModule, module, + 'process.mainModule should === module'); +// assert that it's *not* the main module in the required module. +require('../fixtures/not-main-module.js'); + // require a file with a request that includes the extension var a_js = require('../fixtures/a.js'); assert.equal(42, a_js.number);