mirror of
https://github.com/nodejs/node-v0.x-archive.git
synced 2026-04-28 03:01:10 -04:00
Prefer require.cache over native module cache
This patch changes node's module loading behavior so that the require.cache is always the first place to consider when loading a module. The motivation for this change is to help people who are writing focused tests for their node.js applications, and need a mechanism to inject test doubles to replace native node.js modules.
This commit is contained in:
committed by
Ryan Dahl
parent
a59483bd1d
commit
e27418ca3f
@@ -238,6 +238,9 @@
|
||||
var id = resolved[0];
|
||||
var filename = resolved[1];
|
||||
|
||||
var cachedModule = moduleCache[filename];
|
||||
if (cachedModule) return cachedModule.exports;
|
||||
|
||||
// With natives id === request
|
||||
// We deal with these first
|
||||
if (natives[id]) {
|
||||
@@ -253,9 +256,6 @@
|
||||
return requireNative(id);
|
||||
}
|
||||
|
||||
var cachedModule = moduleCache[filename];
|
||||
if (cachedModule) return cachedModule.exports;
|
||||
|
||||
var module = new Module(id, parent);
|
||||
moduleCache[filename] = module;
|
||||
module.load(filename);
|
||||
|
||||
22
test/simple/test-require-cache.js
Normal file
22
test/simple/test-require-cache.js
Normal file
@@ -0,0 +1,22 @@
|
||||
var common = require('../common');
|
||||
var assert = require('assert');
|
||||
|
||||
(function testInjectFakeModule() {
|
||||
var relativePath = '../fixtures/semicolon';
|
||||
var absolutePath = require.resolve(relativePath);
|
||||
var fakeModule = {};
|
||||
|
||||
require.cache[absolutePath] = {exports: fakeModule};
|
||||
|
||||
assert.strictEqual(require(relativePath), fakeModule);
|
||||
})();
|
||||
|
||||
|
||||
(function testInjectFakeNativeModule() {
|
||||
var relativePath = 'fs';
|
||||
var fakeModule = {};
|
||||
|
||||
require.cache[relativePath] = {exports: fakeModule};
|
||||
|
||||
assert.strictEqual(require(relativePath), fakeModule);
|
||||
})();
|
||||
Reference in New Issue
Block a user