Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Holy grail achieved! Robust require hooking!

The premise is simple: whenever we call the underlying require handler to load
and execute a file, we immediately after verify if our hooks are still there.
If not, they got overwritten, so we can simply update them.

The test server works like a charm now!

As a side benefit, this also expands the watching to support any and all file
extensions, not just .js and .coffee! Because we simply check all registered
extension handlers, and hook into any that we haven't already hooked into.

Suh-weet!
  • Loading branch information...
commit d977854db1292a98a3a3675fceca1ffdcd3b209d 1 parent adf2587
@aseemk aseemk authored
Showing with 26 additions and 15 deletions.
  1. +26 −15 wrapper.js
View
41 wrapper.js
@@ -42,24 +42,35 @@ for (var i=1; i < process.argv.length; i++) {
/** Resolve the location of the main script relative to cwd */
var main = Path.resolve(process.cwd(), arg);
-/** Hook into `require()` */
-function hookInto(ext) {
- var extensionHandler = require.extensions[ext];
- require.extensions[ext] = function(module, filename) {
- if (module.id == main) {
- module.id = '.';
- module.parent = null;
- process.mainModule = module;
- }
- watch(module);
- extensionHandler(module, filename);
- if (ext == '.js' && Path.basename(filename, ext) == 'coffee-script') {
- hookInto('.coffee');
+var handlers = require.extensions;
+var origs = {};
+var hooks = {};
+
+function getOrCreateHook(ext) {
+ return hooks[ext] || (hooks[ext] = function (module, filename) {
+ if (module.id == main) {
+ module.id = '.';
+ module.parent = null;
+ process.mainModule = module;
+ }
+ watch(module);
+ origs[ext](module, filename);
+ updateHooks();
+ });
+}
+
+function updateHooks() {
+ for (var ext in handlers) {
+ var handler = handlers[ext];
+ var hook = getOrCreateHook(ext);
+ if (handler !== hook) {
+ origs[ext] = handler;
+ handlers[ext] = hook;
+ }
}
- };
}
-hookInto('.js');
+updateHooks();
if (Path.extname(main) == '.coffee') {
require('coffee-script');
Please sign in to comment.
Something went wrong with that request. Please try again.