Skip to content

Instantly share code, notes, and snippets.

@mofax
Created March 2, 2017 08:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mofax/3a8fc817bdf7708f433c6c765a8ec744 to your computer and use it in GitHub Desktop.
Save mofax/3a8fc817bdf7708f433c6c765a8ec744 to your computer and use it in GitHub Desktop.
automatically require all files inside a directory via an index.js
'use strict';
let fs = require('fs');
let path = require('path');
function snakeToCamel(s) {
let strings = s.split('_').map((str, index) => {
if (index === 0) return str;
return str.replace(/(^| )(\w)/g, function (x) {
return x.toUpperCase();
});
})
return strings.join('');
}
function asVar(name) {
return snakeToCamel(name.replace('.js', ''));
}
function init() {
let container = {};
let dir = path.dirname(__filename);
let files = fs.readdirSync(dir);
files = files.filter(file => file !== 'index.js' && file.endsWith('.js'));
for (let file of files) {
container[asVar(file)] = require(`./${file}`);
}
return container;
}
module.exports = init();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment