Is it possible to define a custom require method in one module that can be called in another module?
For example, in x/x.js
exports.xrequire = function(path) {
console.log("requiring " + path);
require(path);
};
In y/hello.js
console.log("Hello, world!");
And then in y/y.js
var xrequire = require("../x/x.js").xrequire;
xrequire("hello.js");
When y.js is run, “Hello World” should be printed.
I know this seems like a bad idea, but I do have a legitimate reason to do it. 😉
The issue with this code is that it tries to load x/hello.js, not y/hello.js — I’d like it to work the same as the standard require.
You certainly could do this. It would successfully avoid modifying the global
require.pathsarray which can pose problems at run time, and shouldn’t have an issues with future releases.You should be able to simply set up a model that you simple
requireinto your current app. According to your example x.js should contain.Then you can successfully use your custom
require.I don’t advise this, but if you wanted to be really sneaky, you could override the
requirefunction.I would definitely throughly document this inside your module if you plan to
require😀 this functionality, but it certainly does work.EDIT:
Well you could test for the file and fallback to
requireif it doesn’t exist.I think you could try adding
process.cwdto the beginning of the require path to force looking in the correct directory first. In all honesty this would confuse most developers. I would advise just defining a namespace for your app and creating a special require function that retrieves only that namespaced apps special functions.