Skip to content

Instantly share code, notes, and snippets.

@jed
Created April 4, 2011 14:02
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jed/901674 to your computer and use it in GitHub Desktop.
Save jed/901674 to your computer and use it in GitHub Desktop.
a small module for autorequiring. warning: MAGIC!

autorequire.js

Copyright (c) 2011 Jed Schmidt

a small module for auto-importing modules in node.js.

usage

require( "./autorequire" )
require.auto( <module-name> )

background

autorequire.js is for the terminally lazy. it turns boilerplate code like this:

http = require( 'http' );
https = require( 'https' );
url = require( 'url' );
path = require( 'path' );
util = require( 'util' );
crypto = require( 'crypto' );

into this:

http, https, url, path, util, crypto;

it does this by wrapping your module in a closure, like this:

!function( http, https, url, path, util, crypto ) {
  
  // your original code here
  
}.apply( this, [ 'http', 'https', 'url', 'path', 'util', 'crypto' ].map( require ) )

basically, it attempts to load your module repeatedly, adding a new argument to the list every time a not_defined error is thrown. once all your symbols are there, it compiles and executes the module.

this module was born from a (fab) brainstorm, and is a prototype not really meant for serious use. that said, if you think it could be useful and would like me to npm it, lemme know.

var fs = require( "fs" )
require.auto = function( name ) {
var path = require.resolve( name )
, data = fs.readFileSync( path, "utf8" )
return function autorequire() {
var args = [].slice.call( arguments )
, fn = Function.apply( Function, args )
, ret = [
"!",
fn,
".apply( this, ",
JSON.stringify( args.slice( 0, -1 ) ),
".map( require ) )"
].join( "" )
try { ret = module._compile( ret, path ) }
catch( e ) {
if ( e.type != "not_defined" ) throw e
args.splice( -1, 0, e.arguments[ 0 ] )
return autorequire.apply( this, args )
}
return ret
}( data )
}
// using `require` on this file will throw a `not_defined` error
// using `require.auto` on this file will work as expected
// declare these anywhere in the first tick
assert, repl, url;
assert.equal( assert, require( "assert" ) )
assert.equal(
url.parse( "http://nodejs.org" ).hostname,
"nodejs.org"
)
repl.start( "> " )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment