Skip to content
This repository was archived by the owner on Apr 22, 2023. It is now read-only.
This repository was archived by the owner on Apr 22, 2023. It is now read-only.

Make require a public property of module #1281

@TrevorBurnham

Description

@TrevorBurnham

When Node gives you a module instance, it comes with a require function. The two are linked to each other internally. So if you modify, for instance, module.filename, that affects the relative path used by require. But there's no way to get the require function corresponding to a given module (or vice versa). That's a pain if you want to do something like

sandbox = {module: new Module, require: /* what should go here? */);
vm.runInNewContext(code, sandbox);

This technique is used by CoffeeScript for its REPL, which led to some issues. The current workaround is to construct a new require that mimicks the one in the sandbox.module:

sandbox.require = _require = (path) -> Module._load path, _module
_require[r] = require[r] for r in Object.getOwnPropertyNames require
_require.paths = _module.paths = Module._nodeModulePaths process.cwd()
_require.resolve = (request) -> Module._resolveFilename request, _module

Obviously it'd be a lot less work to just write sandbox.require = sandbox.module.require.

Any reason not to expose require as a property of module? I believe this would just be a one-line change to module.js:

function require(path) {

to

self.require = function require(path) {

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions