Skip to content

Commit 8c9320e

Browse files
committed
src: fix module search path for preload modules
When the preload module is not a abs/relative path, we should use the standard search mechanism of looking into the node_modules folders outwards. The current working directory is deemed to be the 'requiring module', i.e. parent. The search path starts from cwd outwards. Fixes: #1803
1 parent 98649fd commit 8c9320e

File tree

3 files changed

+26
-4
lines changed

3 files changed

+26
-4
lines changed

lib/module.js

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -508,6 +508,19 @@ Module.requireRepl = function() {
508508
return Module._load('internal/repl', '.');
509509
};
510510

511+
Module._preloadModules = function(requests) {
512+
if (requests) {
513+
// Preloaded modules have a dummy parent module which is deemed to exist
514+
// in the current working directory. This seeds the search path for
515+
// preloaded modules.
516+
var parent = new Module('internal/preload', null);
517+
parent.paths = Module._nodeModulePaths(process.cwd());
518+
requests.forEach(function(request) {
519+
Module._load(request, parent, false);
520+
});
521+
}
522+
};
523+
511524
Module._initPaths();
512525

513526
// backwards compatibility

src/node.js

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -858,10 +858,7 @@
858858
// Load preload modules
859859
startup.preloadModules = function() {
860860
if (process._preload_modules) {
861-
var Module = NativeModule.require('module');
862-
process._preload_modules.forEach(function(module) {
863-
Module._load(module);
864-
});
861+
NativeModule.require('module')._preloadModules(process._preload_modules);
865862
}
866863
};
867864

test/fixtures/cluster-preload.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,15 @@
1+
var assert = require('assert');
2+
3+
// https://github.com/nodejs/io.js/issues/1803
4+
// this module is used as a preload module. It should have a parent with the
5+
// module search paths initialized from the current working directory
6+
assert.ok(module.parent);
7+
var expectedPaths = require('module')._nodeModulePaths(process.cwd());
8+
assert.ok(module.parent.paths.length === expectedPaths.length &&
9+
module.parent.paths.every(function(e,i) {
10+
return e === expectedPaths[i];
11+
}));
12+
113
var cluster = require('cluster');
214
cluster.isMaster || process.exit(42 + cluster.worker.id); // +42 to distinguish
315
// from exit(1) for other random reasons

0 commit comments

Comments
 (0)