Skip to content

Instantly share code, notes, and snippets.

@jmakeig
Last active December 3, 2016 19:13
Show Gist options
  • Select an option

  • Save jmakeig/cc214acb1477f1973b2f96086ae99a52 to your computer and use it in GitHub Desktop.

Select an option

Save jmakeig/cc214acb1477f1973b2f96086ae99a52 to your computer and use it in GitHub Desktop.
Proof-Of-Concept that overrides the global require() function in MarkLogic to (eventually) operate like Node
// IIFE to avoid polluting global scope.
(function() {
/** {@link https://nodejs.org/api/modules.html#modules_all_together}
/*
require(X) from module at path Y
1. If X is a core module,
a. return the core module
b. STOP
2. If X begins with './' or '/' or '../'
a. LOAD_AS_FILE(Y + X)
b. LOAD_AS_DIRECTORY(Y + X)
3. LOAD_NODE_MODULES(X, dirname(Y))
4. THROW "not found"
LOAD_AS_FILE(X)
1. If X is a file, load X as JavaScript text. STOP
2. If X.js is a file, load X.js as JavaScript text. STOP
3. If X.json is a file, parse X.json to a JavaScript Object. STOP
4. If X.node is a file, load X.node as binary addon. STOP
LOAD_AS_DIRECTORY(X)
1. If X/package.json is a file,
a. Parse X/package.json, and look for "main" field.
b. let M = X + (json main field)
c. LOAD_AS_FILE(M)
2. If X/index.js is a file, load X/index.js as JavaScript text. STOP
3. If X/index.json is a file, parse X/index.json to a JavaScript object. STOP
4. If X/index.node is a file, load X/index.node as binary addon. STOP
LOAD_NODE_MODULES(X, START)
1. let DIRS=NODE_MODULES_PATHS(START)
2. for each DIR in DIRS:
a. LOAD_AS_FILE(DIR/X)
b. LOAD_AS_DIRECTORY(DIR/X)
NODE_MODULES_PATHS(START)
1. let PARTS = path split(START)
2. let I = count of PARTS - 1
3. let DIRS = []
4. while I >= 0,
a. if PARTS[I] = "node_modules" CONTINUE
b. DIR = path join(PARTS[0 .. I] + "node_modules")
c. DIRS = DIRS + DIR
d. let I = I - 1
5. return DIRS
*/
const _require = require;
/**
* Overrides the default `require()` global to implement
* custom path resolution logic.
*
* @param {string} path - The path to load
* @returns {*} - `module.exports` from the included module
* @throws {Error} - Rethrows underlying {@link Error} if `path` can’t be resolved
*/
require = function(path) {
const steps = path.split(/[\/\\]/);
if(isRelative(path)) { return _require(path); }
try {
return _require('' + path);
} catch(error) {
if('XDMP-MODNOTFOUND' === error.name) {
return _require(path + '/index.js')
}
throw error;
}
};
function isRelative(path) {
return /^\.{1,2}?[\\\/]/.test(path);
}
function resolve(path) { };
/** {@link https://nodejs.org/api/globals.html#globals_require_resolve} */
require.resolve = resolve;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment