or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-require-all

An easy way to require all files within a directory.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/require-all@3.0.x

To install, run

npx @tessl/cli install tessl/npm-require-all@3.0.0

index.mddocs/

require-all

require-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.

Package Information

  • Package Name: require-all
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install require-all

Core Imports

const requireAll = require('require-all');

Basic Usage

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
// }

Capabilities

Main Function

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(); }
});

Configuration Options

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;
}

dirname

  • Type: string
  • Required: Yes
  • Description: Path to the directory to require files from

filter

  • Type: RegExp | Function
  • Default: /^([^\.].*)\.js(on)?$/ (matches .js and .json files, excluding hidden files)
  • Description: Determines which files to require and extracts property names
  • RegExp: Uses capture groups to extract property names. If no capture group, uses full match
  • Function: (filename: string) => string | falsy - return falsy to ignore file, string to use as property name

Filter 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
}

excludeDirs

  • Type: RegExp | boolean
  • Default: /^\./ (excludes hidden directories)
  • Description: Pattern to exclude directories from recursive traversal
  • Set to false to disable directory exclusion entirely

recursive

  • Type: boolean
  • Default: true
  • Description: Whether to recursively traverse subdirectories

resolve

  • Type: Function
  • Default: Identity function (returns input unchanged)
  • Description: Function to transform required modules
  • Function signature: (module: any) => any

Resolve Examples:

// Instantiate constructor functions
resolve: function(Constructor) {
  return new Constructor();
}

// Call function with arguments
resolve: function(fn) {
  return fn('arg1', 'arg2');
}

map

  • Type: Function
  • Default: Identity function (returns input unchanged)
  • Description: Function to transform file/directory names to property names
  • Function signature: (name: string, filepath: string) => string

Map 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();
  });
}

Return Value Structure

The function returns an object where:

  • Keys are property names derived from file/directory names (processed through filter and map)
  • Values are the required modules (potentially transformed via resolve)
  • Nested directories create nested object structures
  • Empty directories are excluded from results

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 }
  }
}

Usage Examples

Constructor Instantiation

Automatically instantiate exported constructor functions:

const controllers = requireAll({
  dirname: __dirname + '/controllers',
  filter: /(.+Controller)\.js$/,
  resolve: function(Controller) {
    return new Controller();
  }
});

Property Name Transformation

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();
    });
  }
});

Custom File Filtering

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
  }
});

Directory Exclusion

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
});

Error Handling

The function uses Node.js built-in file system operations and will throw errors for:

  • Non-existent directories: ENOENT error when dirname doesn't exist
  • Permission issues: EACCES error when lacking read permissions
  • Invalid file paths: Various filesystem errors for malformed paths
  • Module loading errors: Any errors thrown by required files will propagate

Error 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);
  }
}