This repository has been archived by the owner on Apr 22, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7.3k
Make require
a public property of module
#1281
Labels
Comments
ghost
assigned felixge
Jul 9, 2011
Yeah, it does have a certain elegant symmetry to module.exports. Not sure about putting it in v0.4, since it's new API, but it should be done, I think. diff --git a/lib/module.js b/lib/module.js
index 11c5189..b725afa 100644
--- a/lib/module.js
+++ b/lib/module.js
@@ -336,6 +336,11 @@ Module.prototype.load = function(filename) {
};
+Module.prototype.require = function(path) {
+ return Module._load(path, this);
+};
+
+
// Returns exception if any
Module.prototype._compile = function(content, filename) {
var self = this;
@@ -343,7 +348,7 @@ Module.prototype._compile = function(content, filename) {
content = content.replace(/^\#\!.*/, '');
function require(path) {
- return Module._load(path, self);
+ return self.require(path);
}
require.resolve = function(request) { |
To answer the "what goes here?" question in the op: var module = new Module(".");
var sandbox = {module: module, require: function (p) { return Module._load(p, module) }, exports: module.exports };
vm.runInNewContext(code, sandbox); |
@isaacs: Ok, any reason for not landing this in 0.5 right now? |
@felixge Is that a +1 LGTM review? I'll add some tests and docs for it today. |
@isaacs: Yes, the patch looks great, can't await to have this : ). |
Sign up for free
to subscribe to this conversation on GitHub.
Already have an account?
Sign in.
When Node gives you a
module
instance, it comes with arequire
function. The two are linked to each other internally. So if you modify, for instance,module.filename
, that affects the relative path used byrequire
. But there's no way to get therequire
function corresponding to a givenmodule
(or vice versa). That's a pain if you want to do something likeThis 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 thesandbox.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 ofmodule
? I believe this would just be a one-line change to module.js:to
The text was updated successfully, but these errors were encountered: