An easy way to require all files within a directory.
npx @tessl/cli install tessl/npm-require-all@3.0.0require-all is a Node.js utility library that provides an easy way to require all files within a directory. It offers flexible configuration options including recursive directory traversal, file filtering through regular expressions or functions, custom property name mapping, and automatic object construction from required modules.
npm install require-allconst requireAll = require('require-all');const requireAll = require('require-all');
// Simple usage - require all .js and .json files from a directory
const modules = requireAll(__dirname + '/lib');
// Advanced usage with configuration
const controllers = requireAll({
dirname: __dirname + '/controllers',
filter: /(.+Controller)\.js$/,
excludeDirs: /^\.(git|svn)$/,
recursive: true
});
// Result structure:
// {
// HomeController: { ... }, // contents of HomeController.js
// UserController: { ... }, // contents of UserController.js
// // ... other controller modules
// }The primary export that requires all files from a directory based on provided options.
/**
* Require all files from a directory with flexible configuration options
* @param {string|object} options - Directory path as string, or configuration object
* @returns {object} Object containing all required modules mapped to property names
*/
function requireAll(options);Simple String Usage:
const modules = requireAll('/path/to/directory');Advanced Object Configuration:
const modules = requireAll({
dirname: '/path/to/directory',
filter: /(.+Controller)\.js$/,
excludeDirs: /^\.(git|svn)$/,
recursive: true,
resolve: function(module) { return new module(); },
map: function(name, filepath) { return name.toLowerCase(); }
});When using the object configuration format, the following options are available:
interface RequireAllOptions {
/** Path to the directory to require files from (required) */
dirname: string;
/** Filter to determine which files to require and how to name them */
filter?: RegExp | ((filename: string) => string | undefined);
/** Pattern to exclude directories from recursive traversal */
excludeDirs?: RegExp | boolean;
/** Whether to recursively traverse subdirectories */
recursive?: boolean;
/** Function to transform required modules (e.g., instantiate constructors) */
resolve?: (module: any) => any;
/** Function to transform file/directory names to property names */
map?: (name: string, filepath: string) => string;
}stringRegExp | Function/^([^\.].*)\.js(on)?$/ (matches .js and .json files, excluding hidden files)(filename: string) => string | falsy - return falsy to ignore file, string to use as property nameFilter Examples:
// Only require files ending in "Controller.js", use captured name
filter: /(.+Controller)\.js$/
// Custom function filter
filter: function(fileName) {
const parts = fileName.split('-');
if (parts[1] !== 'Controller.js') return;
return parts[0]; // Use first part as property name
}RegExp | boolean/^\./ (excludes hidden directories)false to disable directory exclusion entirelybooleantrueFunction(module: any) => anyResolve Examples:
// Instantiate constructor functions
resolve: function(Constructor) {
return new Constructor();
}
// Call function with arguments
resolve: function(fn) {
return fn('arg1', 'arg2');
}Function(name: string, filepath: string) => stringMap Examples:
// Convert snake_case to camelCase
map: function(name, path) {
return name.replace(/_([a-z])/g, function(m, c) {
return c.toUpperCase();
});
}
// Convert dashes to underscores
map: function(name, path) {
return name.replace(/-([A-Za-z])/, function(m, c) {
return '_' + c.toLowerCase();
});
}The function returns an object where:
filter and map)resolve)Example directory structure:
controllers/
├── HomeController.js // exports { index: 1, show: 2 }
├── UserController.js // exports { create: 3, update: 4 }
└── admin/
└── AdminController.js // exports { dashboard: 5 }Resulting object:
{
HomeController: { index: 1, show: 2 },
UserController: { create: 3, update: 4 },
admin: {
AdminController: { dashboard: 5 }
}
}Automatically instantiate exported constructor functions:
const controllers = requireAll({
dirname: __dirname + '/controllers',
filter: /(.+Controller)\.js$/,
resolve: function(Controller) {
return new Controller();
}
});Transform file names to desired property names:
const controllers = requireAll({
dirname: __dirname + '/controllers',
filter: /(.+Controller)\.js$/,
map: function(name, path) {
// Convert "main-Controller" to "mainController"
return name.replace(/-([A-Z])/, function(m, c) {
return c.toLowerCase();
});
}
});Use a function to implement complex filtering logic:
const modules = requireAll({
dirname: __dirname + '/modules',
filter: function(fileName) {
// Only require files with specific naming pattern
const parts = fileName.split('-');
if (parts.length !== 2 || parts[1] !== 'module.js') {
return; // Skip this file
}
return parts[0]; // Use first part as property name
}
});Control which directories to exclude from traversal:
// Exclude .git and .svn directories
const modules = requireAll({
dirname: __dirname + '/src',
excludeDirs: /^\.(git|svn)$/
});
// Include all directories (disable exclusion)
const modules = requireAll({
dirname: __dirname + '/src',
excludeDirs: false
});The function uses Node.js built-in file system operations and will throw errors for:
ENOENT error when dirname doesn't existEACCES error when lacking read permissionsError handling example:
try {
const modules = requireAll({
dirname: __dirname + '/controllers'
});
} catch (error) {
if (error.code === 'ENOENT') {
console.error('Controllers directory not found');
} else {
console.error('Error loading modules:', error.message);
}
}