Skip to content

Instantly share code, notes, and snippets.

@robinduckett
Created April 12, 2012 08:33
Show Gist options
  • Save robinduckett/2365630 to your computer and use it in GitHub Desktop.
Save robinduckett/2365630 to your computer and use it in GitHub Desktop.
Namespacing for Node.js
path = require('path')
loader = (ns) ->
ns = ns.toString()
parts = ns.split /\./
requirePath = ns.replace /\./g, '/'
try
requirePath = path.dirname(require.main.filename) + '/' + requirePath
require requirePath
catch err
try
mod = loader(parts[0..parts.length-2].join('.'))[parts[parts.length-1]] if parts.length - 2 > 0
catch moderr
throw new Error 'namespace (' + ns + ') invalid'
if mod is undefined
throw new Error 'namespace (' + ns + ') invalid'
else
mod
module.exports = (ns) ->
try
loader ns
catch err
console.error err.message
process.exit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment