Skip to content

Clearing require.cache of native addon makes it throw when required later. #6160

Closed
@bengl

Description

@bengl
  • Version: 5.10.1 (going back to around 0.12, I think)
  • Platform: Darwin 14.5.0 Darwin Kernel Version 14.5.0: Wed Jul 29 02:26:53 PDT 2015; root:xnu-2782.40.9~1/RELEASE_X86_64 x86_64 i386
  • Subsystem: module/require

require-ing a native addon after it has already been required and then removed from the require cache results in an error, rather than simply providing the module again.

For example, I inserted the following code into a test called require-cache-clear, modelled after test/addons/hello-world, using a dummy native module:

'use strict'
require('../../common')
const assert = require('assert')
const nativeMod = './build/Release/binding'

require(nativeMod)
delete require.cache[require.resolve(nativeMod)]
assert.doesNotThrow(()=>require(nativeMod))

The resulting error is:

Error: Module did not self-register.
    at Error (native)
    at Object.Module._extensions..node (module.js:443:18)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:313:12)
    at Module.require (module.js:366:17)
    at require (internal/module.js:16:19)
    at assert.doesNotThrow (/Users/bengl/node/test/addons/require-cache-clear/test.js:8:25)
    at _tryBlock (assert.js:305:5)
    at _throws (assert.js:324:12)
    at Function.assert.doesNotThrow (assert.js:352:3)

A quick Google search informs me that such errors are usually the result of version mismatches, and a node-gyp rebuild will solve them. This isn't the case here.

We came across this due to mockery's clearing of the cache. I suspect that folks using this or other modules that manipulate require.cache/Module._cache are going to (or have already) run into this at some point or another.

My best guess is that this might be related to this comment here by @bnoordhuis.

Metadata

Metadata

Assignees

No one assigned

    Labels

    docIssues and PRs related to the documentations.moduleIssues and PRs related to the module subsystem.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions