Skip to content

Instantly share code, notes, and snippets.

@Xananax
Created February 19, 2018 21:56
Show Gist options
  • Save Xananax/b734f43f3045440ba87a8020a51c138e to your computer and use it in GitHub Desktop.
Save Xananax/b734f43f3045440ba87a8020a51c138e to your computer and use it in GitHub Desktop.
Require all files in a node project directory
const handlers = ( ( root = '', handlers = {} ) => {
const path = require('path')
const dir = path.join( __dirname, root ) // skip calling file (if it is in the same dir)
const index_file = path.join( dir, 'index.js' ) // skip index.js
require('fs').readdirSync(dir)
.filter( file => {
const curr = path.join(dir,file)
return ( /\.js/.test(file) && curr !== __filename && curr !== index_file )
} )
.map( file => file.replace(/\.js/,'') )
.forEach( file => handlers[file] = require(`./${root}` + file))
return handlers;
}
)()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment