Skip to content

Commit 6df0a6a

Browse files
sonicdoebendrucker
authored andcommitted
Only remove non-native modules from cache (#149)
Closes #108
1 parent c0b274b commit 6df0a6a

File tree

4 files changed

+38
-1
lines changed

4 files changed

+38
-1
lines changed

.travis.yml

+9-1
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,12 @@ language: node_js
22
node_js:
33
- '0.10'
44
- '4'
5-
- '6'
5+
- '6'
6+
env:
7+
- CXX=g++-4.8
8+
addons:
9+
apt:
10+
sources:
11+
- ubuntu-toolchain-r-test
12+
packages:
13+
- g++-4.8

lib/proxyquire.js

+17
Original file line numberDiff line numberDiff line change
@@ -220,8 +220,25 @@ Proxyquire.prototype._disableGlobalCache = function() {
220220
var cache = require.cache;
221221
require.cache = Module._cache = {};
222222

223+
for (var id in cache) {
224+
// Keep native modules (i.e. `.node` files).
225+
// Otherwise, Node.js would throw a “Module did not self-register”
226+
// error upon requiring it a second time.
227+
// See https://github.com/nodejs/node/issues/5016.
228+
if (/\.node$/.test(id)) {
229+
require.cache[id] = cache[id];
230+
}
231+
}
232+
223233
// Return a function that will undo what we just did
224234
return function() {
235+
// Keep native modules which were added to the cache in the meantime.
236+
for (var id in require.cache) {
237+
if (/\.node$/.test(id)) {
238+
cache[id] = require.cache[id]
239+
}
240+
}
241+
225242
require.cache = Module._cache = cache;
226243
};
227244
};

package.json

+1
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
"license": "MIT",
2626
"devDependencies": {
2727
"mocha": "~3.1",
28+
"native-hello-world": "^1.0.0",
2829
"should": "~3.3",
2930
"sinon": "~1.9"
3031
},

test/proxyquire-global.js

+11
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,17 @@ describe('global flags set', function () {
3939
assert.equal(realFoo(), false);
4040
assert.equal(proxiedFoo(), true);
4141
});
42+
43+
it('should not throw when a native module is required a second time', function () {
44+
var stubs = {
45+
'foo': {
46+
'@global': true
47+
}
48+
};
49+
50+
proxyquire('native-hello-world', stubs)
51+
proxyquire('native-hello-world', stubs)
52+
})
4253
});
4354

4455
describe('global flags not set', function () {

0 commit comments

Comments
 (0)