My JavaScript book is out! Don't miss the opportunity to upgrade your beginner or average dev skills.

Thursday, October 06, 2011

implicit require in node.js

playing with Harmony Proxy I came out with a simple snippet:

var module = (function create(
namespace, handler, module, Proxy
) {
// ------------------------------------
// (C) WebReflection - MitStyle License
// ------------------------------------
// @dependency npm install node-proxy
// ------------------------------------
// var sys = module.sys;
// sys.print("it works!");
// var yet = sys.nonexisting.yet;
// yet.doStuff();
// ------------------------------------
return Proxy.create({
get: function (receiver, name) {
if (!module.hasOwnProperty(name)) {
var key = namespace ?
namespace + "/" + name :
name
;
module[name] = require(key);
handler[name] = create(key, {}, module[name], Proxy);
return handler[name];
} else {
return module[name];
}
}
});
}("", {}, global, global.Proxy || require("node-proxy")));
view raw module.js hosted with ❤ by GitHub

The aim of above snippet is to forget the usage of require ... here some example:

module.sys.puts("Hello implicit require");

var fs = module.fs;
fs.stat( ... );

It's compatible with nested namespaces too and if there are non JS chars in the middle ... well:
var Proxy = module["node-proxy"];

1 comment:

Anonymous said...

Clever but doesn't actually save any typing...