Skip to content

Instantly share code, notes, and snippets.

@jubianchi
Last active October 5, 2015 07:48
Show Gist options
  • Save jubianchi/a5b2c5a9a47926366371 to your computer and use it in GitHub Desktop.
Save jubianchi/a5b2c5a9a47926366371 to your computer and use it in GitHub Desktop.
POC nodejs autoloader - `node --harmony_proxies index.js`
"use strict";
module.exports = function autoload() {
try {
require.resolve("harmony-reflect");
} catch (err) {
throw new Error("You should install harmony-reflect module and use the --harmony_proxies flag to use this feature");
}
require("harmony-reflect");
global.__proto__ = new Proxy(
Object.getPrototypeOf(global.__proto__),
{
get: (target, key) => {
if (key !== "v8debug" && target[key] === undefined) {
let path = key.toLowerCase().replace("_", "/");
try {
target[key] = require(path);
} catch (e) {
target[key] = require(__dirname + "/" + path);
}
}
return target[key];
}
}
);
};
"use strict";
class Bar extends Foo {}
module.exports = Bar;
"use strict";
class Foo {}
module.exports = Foo;
"use strict";
let autoload = require("./autoload");
autoload();
console.log(fs.readFileSync); // [Function]
console.log(new Bar()); // Bar {}
console.log(new Bar() instanceof Foo); // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment