### Install directory-import Source: https://github.com/aniname/directory-import/blob/master/README.md Install the package using npm. This is the first step before using the module in your project. ```bash npm install directory-import ``` -------------------------------- ### Simple usage example Source: https://github.com/aniname/directory-import/blob/master/README.md A straightforward example demonstrating the basic usage of directoryImport to import modules from a sample directory. ```javascript const { directoryImport } = require('directory-import'); const importedModules = directoryImport('./sample-directory'); console.info(importedModules); ``` -------------------------------- ### Minimal Directory Import Configuration Source: https://github.com/aniname/directory-import/blob/master/_autodocs/configuration.md Use this snippet for a basic setup with default options. It imports all files from the specified target directory. ```javascript const { directoryImport } = require('directory-import'); // Uses all defaults const modules = directoryImport({ targetDirectoryPath: './src' }); ``` -------------------------------- ### Express Route Loader Example Source: https://github.com/aniname/directory-import/blob/master/_autodocs/index.md This example demonstrates how to dynamically load Express route handlers from a directory. It imports all modules from the './routes' directory and applies them as handlers if they are functions. ```javascript const express = require('express'); const { directoryImport } = require('directory-import'); const app = express(); const routes = directoryImport('./routes'); Object.values(routes).forEach(handler => { if (typeof handler === 'function') { handler(app); } }); ``` -------------------------------- ### Configuration Validation Example Source: https://github.com/aniname/directory-import/blob/master/_autodocs/configuration.md Demonstrates how to catch errors during configuration validation. This snippet attempts to use an invalid import mode, triggering a catch block. ```javascript const { directoryImport } = require('directory-import'); try { directoryImport('./src', { importMode: 'invalid' // Invalid mode }); } catch (error) { // Error during validation/parsing, not during import } ``` -------------------------------- ### TypeScript Import Example Source: https://github.com/aniname/directory-import/blob/master/_autodocs/types.md Demonstrates how to import and use various types from the 'directory-import' package in a TypeScript project. Includes setting up options and a callback function for module imports. ```typescript import { ImportedModules, ImportedModulesPublicOptions, ImportModulesCallback, ImportModulesMode, ModuleName, ModulePath, ModuleData, ModuleIndex } from 'directory-import'; const options: ImportedModulesPublicOptions = { targetDirectoryPath: './src', importMode: 'async' }; const callback: ImportModulesCallback = (name, path, data, index) => { console.log(name, path, index); }; const modules: ImportedModules = await directoryImport(options, callback); ``` -------------------------------- ### Plugin Loader Configuration Source: https://github.com/aniname/directory-import/blob/master/_autodocs/configuration.md Configure the import process to load specific plugin files. This example uses a custom import pattern and enables subdirectory inclusion. ```javascript const { directoryImport } = require('directory-import'); const plugins = directoryImport({ targetDirectoryPath: './plugins', importPattern: /\.plugin\.js$/, includeSubdirectories: true, forceReload: process.env.NODE_ENV === 'development' }); ``` -------------------------------- ### Code Examples Coverage by Type Source: https://github.com/aniname/directory-import/blob/master/_autodocs/REFERENCE-COVERAGE.md Breaks down the coverage of code examples by type, including basic usage, configuration, error handling, advanced patterns, type usage, and integration patterns, along with their respective counts and locations. ```markdown | Type | Count | Location | |------|-------|---| | Basic usage | 15 | Throughout | | Configuration | 10 | configuration.md | | Error handling | 12 | errors.md | | Advanced patterns | 10 | api-reference/directoryImport.md | | Type usage | 8 | types.md | | Integration patterns | 5 | api-reference/directoryImport.md | ``` -------------------------------- ### Process Environment Integration for Configuration Source: https://github.com/aniname/directory-import/blob/master/_autodocs/configuration.md Integrate environment variables to dynamically configure directory import options. This allows for flexible setup across different environments. ```javascript const { directoryImport } = require('directory-import'); const options = { targetDirectoryPath: process.env.MODULES_DIR || './src/modules', importMode: process.env.ASYNC_IMPORT === 'true' ? 'async' : 'sync', forceReload: process.env.NODE_ENV !== 'production', limit: parseInt(process.env.MODULE_LIMIT || '1000', 10), includeSubdirectories: process.env.INCLUDE_SUBDIRS !== 'false' }; const modules = directoryImport(options); ``` -------------------------------- ### Conditional Configuration Logic Source: https://github.com/aniname/directory-import/blob/master/_autodocs/configuration.md Implement conditional logic to set import options based on the environment. This example returns different configurations for production and development environments. ```javascript const { directoryImport } = require('directory-import'); function getImportOptions(environment) { const baseOptions = { targetDirectoryPath: './src/handlers' }; if (environment === 'production') { return { ...baseOptions, importMode: 'sync', forceReload: false, limit: Infinity }; } return { ...baseOptions, importMode: 'async', forceReload: true, limit: 50 // Limit for faster feedback during development }; } const modules = directoryImport(getImportOptions(process.env.NODE_ENV)); ``` -------------------------------- ### Asynchronous Plugin System Loading Source: https://github.com/aniname/directory-import/blob/master/_autodocs/api-reference/directoryImport.md Loads plugins asynchronously from a directory. It initializes plugins that expose an `init` function. This is useful for plugins that require asynchronous setup. ```javascript const { directoryImport } = require('directory-import'); async function loadPlugins(pluginDirectory) { const plugins = await directoryImport(pluginDirectory, 'async'); for (const [path, plugin] of Object.entries(plugins)) { if (plugin.init && typeof plugin.init === 'function') { await plugin.init(); console.log(`Initialized plugin: ${path}`); } } return plugins; } ``` -------------------------------- ### ImportedModulesPublicOptions Example Usage Source: https://github.com/aniname/directory-import/blob/master/_autodocs/types.md Shows how to configure advanced options for directoryImport, such as specifying a target directory, a file import pattern, and enabling asynchronous mode. ```typescript const options: ImportedModulesPublicOptions = { targetDirectoryPath: './src/plugins', importPattern: /plugin\.js$/, includeSubdirectories: true, importMode: 'async', limit: 20, forceReload: false }; const modules = directoryImport(options); ``` -------------------------------- ### Selective Directory Import Source: https://github.com/aniname/directory-import/blob/master/_autodocs/configuration.md Import only specific configuration files from a directory. This example disables subdirectory inclusion and sets a limit on the number of files to import. ```javascript const { directoryImport } = require('directory-import'); const config = directoryImport({ targetDirectoryPath: './config', importPattern: /config\..*\.js$/, includeSubdirectories: false, limit: 50 }); ``` -------------------------------- ### Development Hot-Reloading with Force Reload Source: https://github.com/aniname/directory-import/blob/master/_autodocs/configuration.md This example demonstrates using `forceReload` in conjunction with `process.env.NODE_ENV` to enable hot-reloading of routes in a development environment. When not in production, modules are reloaded from disk on each import. ```javascript // Hot-reload development server const express = require('express'); const { directoryImport } = require('directory-import'); const app = express(); // Load routes with forced reload in development const routes = directoryImport('./routes', { importMode: 'sync', forceReload: process.env.NODE_ENV !== 'production' }); routes.forEach((route) => { app.use(route); }); ``` -------------------------------- ### Import modules synchronously (ES Modules) Source: https://github.com/aniname/directory-import/blob/master/README.md Import modules from a specified directory using ES Module syntax. This is the equivalent of the CommonJS example but for modern JavaScript environments. ```typescript import { directoryImport } from 'directory-import'; const importedModules = directoryImport('./path/to/directory'); // Outputs an object with imported modules // For example: { modulePath1: module1, modulePath2: module2, ... } console.log(importedModules); ``` -------------------------------- ### Directory Import - Synchronous and Asynchronous Examples Source: https://github.com/aniname/directory-import/blob/master/_autodocs/api-reference/directoryImport.md Demonstrates how to use directoryImport in both synchronous and asynchronous modes. The synchronous mode returns the modules object directly, while the asynchronous mode returns a Promise that resolves to the modules object. ```javascript const modules = directoryImport('./src', 'sync'); // { '/file1.js': {...}, '/subdir/file2.ts': {...} } const modulesPromise = directoryImport('./src', 'async'); modulesPromise.then(modules => { // Same shape as sync result }); ``` -------------------------------- ### Handling ENOENT: Directory Not Found Source: https://github.com/aniname/directory-import/blob/master/_autodocs/errors.md Catch 'ENOENT' errors when the specified directory does not exist. This example shows how to check the error code and log a specific message. ```javascript const { directoryImport } = require('directory-import'); try { const modules = directoryImport('./nonexistent'); } catch (error) { if (error.code === 'ENOENT') { console.error('Directory not found:', error.path); } } ``` -------------------------------- ### Directory Import - Subdirectory Structure Example Source: https://github.com/aniname/directory-import/blob/master/_autodocs/api-reference/directoryImport.md Illustrates the structure of the imported modules object based on the directory structure and the 'includeSubdirectories' option. When true, the relative path includes the full subdirectory structure. ```json { '/index.js': {...}, '/handlers/user.js': {...}, '/handlers/product.js': {...} } ``` -------------------------------- ### ImportedModules Example Usage Source: https://github.com/aniname/directory-import/blob/master/_autodocs/types.md Demonstrates how to use the ImportedModules type to access module exports. Shows accessing properties from JavaScript, TypeScript, and JSON files. ```typescript const modules: ImportedModules = { '/index.js': { main: true }, '/utils.js': { helper: () => {} }, '/handlers/user.ts': { userHandler: async () => {} }, '/config.json': { port: 3000, host: 'localhost' } }; // Access modules modules['/utils.js'].helper(); modules['/config.json'].port // 3000 ``` -------------------------------- ### Import Modules from Current Directory (Default) Source: https://github.com/aniname/directory-import/blob/master/_autodocs/api-reference/directoryImport.md Use this when you need to import all modules from the current working directory synchronously without any specific filtering or callbacks. Ensure 'directory-import' is installed. ```javascript const { directoryImport } = require('directory-import'); // Import all modules from the current directory const modules = directoryImport(); console.log(modules); // Output: { '/file1.js': {...}, '/file2.ts': {...} } ``` -------------------------------- ### JavaScript Import with JSDoc Example Source: https://github.com/aniname/directory-import/blob/master/_autodocs/types.md Shows how to use JSDoc comments to provide type information for IDEs when using the 'directory-import' package in a JavaScript project. This helps with autocompletion and type checking. ```javascript /** @type {import('directory-import').ImportedModulesPublicOptions} */ const options = { targetDirectoryPath: './src' }; ``` -------------------------------- ### Example: Calling directoryImport without explicit path Source: https://github.com/aniname/directory-import/blob/master/_autodocs/api-reference/internal-modules.md Demonstrates how to call the `directoryImport()` function without specifying a path, relying on stack trace analysis to determine the caller's directory. ```javascript // Works without explicit path — uses caller's directory const modules = directoryImport(); ``` -------------------------------- ### Directory Import with Callback Function Source: https://github.com/aniname/directory-import/blob/master/_autodocs/api-reference/directoryImport.md This example demonstrates how to use the callback function with directoryImport to process each imported module. The callback receives the module's name, path, exported data, and an index. ```javascript const { directoryImport } = require('directory-import'); directoryImport('./src', (name, path, data, index) => { // name: 'utils', path: '/utils.js', data: {...exported properties...}, index: 0 // name: 'handler', path: '/nested/handler.ts', data: function..., index: 1 console.log(`[${index}] Imported ${name} from ${path}`); console.log(`Module exports:`, Object.keys(data)); }); ``` -------------------------------- ### Directory Import Function Documentation Source: https://github.com/aniname/directory-import/blob/master/_autodocs/REFERENCE-COVERAGE.md Details the main `directoryImport` function, including its 8 overloads, parameter types, return specifications, behavior, usage examples, error handling, and integration patterns. ```markdown | Function | Overloads | Parameters | Examples | Error Handling | |----------|-----------|-----------|----------|---| | `directoryImport` | 8 | All documented with types | 20+ | Full coverage | ``` -------------------------------- ### Initialize Default Options Source: https://github.com/aniname/directory-import/blob/master/_autodocs/api-reference/internal-modules.md Shows the initialization of default options for `preparePrivateOptions`, including settings for subdirectory inclusion, import mode, patterns, limits, and caller information. ```typescript const options = getDefaultOptions(); ``` -------------------------------- ### Get Default Options Source: https://github.com/aniname/directory-import/blob/master/_autodocs/api-reference/internal-modules.md Generates a fresh default options object for module imports. This function ensures that default configurations are consistently applied. ```typescript const getDefaultOptions = (): ImportedModulesPrivateOptions => { ... } ``` -------------------------------- ### Import with Configuration Options Source: https://github.com/aniname/directory-import/blob/master/_autodocs/index.md Import modules using a configuration object to specify directory, import mode, and subdirectory inclusion. ```javascript // With configuration const modules = directoryImport({ targetDirectoryPath: './handlers', importMode: 'async', includeSubdirectories: true }); ``` -------------------------------- ### Error Documentation Features Source: https://github.com/aniname/directory-import/blob/master/_autodocs/REFERENCE-COVERAGE.md Describes the features of error documentation, including when errors occur, example code to trigger them, prevention strategies, and handling patterns. ```markdown ✓ **Error Documentation** (9/9 error types) - When error occurs - Example code that triggers it - How to fix it - Prevention strategies - Handling patterns - Test examples ``` -------------------------------- ### Import Modules with Callback from Specified Directory Source: https://github.com/aniname/directory-import/blob/master/README.md Import modules from a specified directory path synchronously and use a callback for each module. Ideal for processing modules from a specific location. ```javascript const { directoryImport } = require('directory-import'); /** * Import modules from the specified directory synchronously and call the provided callback for each imported module. * @param {String} directoryPath - The path to the directory from which you want to import modules. * @param {Function} callback - The callback function to call for each imported module. * @returns {Object} An object containing all imported modules. */ directoryImport('./path/to/directory', (moduleName, modulePath, moduleData) => { // { // moduleName: 'sample-file-1', // modulePath: '/sample-file-1.js', // moduleData: 'This is first sampleFile' // } // ... console.info({ moduleName, modulePath, moduleData }); }); ``` -------------------------------- ### Load Plugins Dynamically Source: https://github.com/aniname/directory-import/blob/master/_autodocs/index.md Loads all modules from a specified directory, executing an 'init' function if present on each module. This is useful for initializing plugins or services. ```javascript const { directoryImport } = require('directory-import'); async function loadPlugins(dir) { const plugins = await directoryImport(dir, 'async'); for (const [path, plugin] of Object.entries(plugins)) { if (plugin.init) { await plugin.init(); } } return plugins; } ``` -------------------------------- ### Import All Modules (Basic) Source: https://github.com/aniname/directory-import/blob/master/_autodocs/index.md Import all modules from a directory. The result is an object where keys are module paths and values are the imported module exports. ```javascript const { directoryImport } = require('directory-import'); const modules = directoryImport('./src'); // Result: { '/file1.js': ..., '/file2.ts': ... } ``` -------------------------------- ### Import Modules with Mode and Callback Source: https://github.com/aniname/directory-import/blob/master/README.md Import modules from a specified directory with a defined mode ('sync' or 'async') and execute a callback for each module. This combines explicit mode control with per-module processing. ```javascript const { directoryImport } = require('directory-import'); /** * Import all modules from the specified directory synchronously or asynchronously and call the provided callback for each imported module. * @param {string} targetDirectoryPath - The path to the directory to import modules from. * @param {'sync'|'async'} mode - The import mode. Can be 'sync' or 'async'. * @param {Function} callback - The callback function to call for each imported module. * @returns {Object} An object containing all imported modules. */ directoryImport('./path/to/directory', 'sync', (moduleName, modulePath, moduleData) => { // { // moduleName: 'sample-file-1', // modulePath: '/sample-file-1.js', // moduleData: 'This is first sampleFile' // } // ... console.info({ moduleName, modulePath, moduleData }); }); ``` -------------------------------- ### Handle Module Not Found Errors Source: https://github.com/aniname/directory-import/blob/master/_autodocs/errors.md Catch MODULE_NOT_FOUND errors when a module attempts to require a non-existent dependency. Install the missing package or check the package.json for correct names. ```javascript // File: src/handler.js const missing = require('nonexistent-package'); const { directoryImport } = require('directory-import'); try { const modules = directoryImport('./src'); } catch (error) { // error.code === 'MODULE_NOT_FOUND' console.error('Missing dependency:', error.message); } ``` -------------------------------- ### Configuration Documentation Features Source: https://github.com/aniname/directory-import/blob/master/_autodocs/REFERENCE-COVERAGE.md Outlines the features of configuration documentation, covering detailed behavior explanations, type and default values, use cases, performance considerations, and related option cross-references. ```markdown ✓ **Configuration Documentation** (6/6 options) - Detailed behavior explanation - Type and default value - Use cases and examples - Performance considerations - Related options cross-references ``` -------------------------------- ### Type Documentation Features Source: https://github.com/aniname/directory-import/blob/master/_autodocs/REFERENCE-COVERAGE.md Details the features of type documentation, including complete type definitions, field tables with descriptions, cross-references, and usage examples for all documented types. ```markdown ✓ **Type Documentation** (11/11 types) - Complete type definition - Field tables with descriptions - Cross-references to where used - Usage examples ``` -------------------------------- ### Handling EISDIR: Path is a File Source: https://github.com/aniname/directory-import/blob/master/_autodocs/errors.md Catch 'EISDIR' errors when the provided path points to a file instead of a directory. The example checks the error code and logs the problematic path. ```javascript const { directoryImport } = require('directory-import'); try { const modules = directoryImport('./single-file.js'); // Passes a file, not directory } catch (error) { if (error.code === 'EISDIR') { console.error('Path is a file, not directory:', error.path); } } ``` -------------------------------- ### Load Configuration Files Source: https://github.com/aniname/directory-import/blob/master/_autodocs/index.md Imports configuration files from a specific directory using a custom import pattern. It then merges all imported configurations into a single object. ```javascript const { directoryImport } = require('directory-import'); const config = directoryImport('./config', { importPattern: /\.config\.js$/, includeSubdirectories: false }); const merged = Object.values(config).reduce((acc, cfg) => ({ ...acc, ...cfg }), {}); ``` -------------------------------- ### Content Statistics Summary Source: https://github.com/aniname/directory-import/blob/master/_autodocs/REFERENCE-COVERAGE.md Provides statistics on the documentation content, including the number of files, lines of markdown, words, code examples, parameter tables, and documented internal functions. ```markdown | Metric | Count | |--------|-------| | **Files** | 7 | | **Total Lines of Markdown** | 3,718 | | **Total Words** | ~15,000 | | **Code Examples** | 60+ | | **Parameter Tables** | 15+ | | **Internal Functions Documented** | 6 | | **Error Patterns** | 10+ | | **Configuration Examples** | 15+ | ``` -------------------------------- ### TypeScript Type Alias: ModulePath Source: https://github.com/aniname/directory-import/blob/master/_autodocs/types.md Represents the relative path to an imported file from the target directory, always starting with a forward slash. Platform-independent, using forward slashes on Windows. ```typescript type ModulePath = string ``` -------------------------------- ### Import Modules with Callback from Current Directory Source: https://github.com/aniname/directory-import/blob/master/README.md Import modules from the current directory synchronously and execute a callback for each imported module. This allows processing each module as it's imported. ```javascript const { directoryImport } = require('directory-import'); /** * Import modules from the current directory synchronously and call the provided callback for each imported module. * @param {Function} callback - The callback function to call for each imported module. * @returns {Object} An object containing all imported modules. */ directoryImport((moduleName, modulePath, moduleData) => { // { // moduleName: 'sample-file-1', // modulePath: '/sample-file-1.js', // moduleData: 'This is first sampleFile' // } // ... console.info({ moduleName, modulePath, moduleData }); }); ``` -------------------------------- ### Import Files and Invoke Function Source: https://github.com/aniname/directory-import/wiki/Examples-of-using Import files from a specified directory synchronously and invoke a callback function for each file, passing its name, path, and data. ```javascript // Import files and invoke function per file directory-import({ path: './routes', method: 'sync' }, (fileName, filePath, fileData) => { console.info({ fileName, filePath, fileData }); }); ``` -------------------------------- ### Handling EACCES: Permission Denied Source: https://github.com/aniname/directory-import/blob/master/_autodocs/errors.md Catch 'EACCES' errors when the process lacks necessary read permissions for a directory or file. The example checks the error code and logs the affected path. ```javascript const { directoryImport } = require('directory-import'); try { const modules = directoryImport('/root/protected'); } catch (error) { if (error.code === 'EACCES') { console.error('Permission denied on:', error.path); } } ``` -------------------------------- ### Default Options Reference Source: https://github.com/aniname/directory-import/blob/master/_autodocs/configuration.md This object shows the default configuration values used by the library when no explicit options are provided. The target directory path is determined dynamically. ```javascript { includeSubdirectories: true, targetDirectoryPath: '[caller directory]', // Determined via stack trace importPattern: /.*/, // Matches all files importMode: 'sync', limit: Infinity, forceReload: false } ``` -------------------------------- ### Import Modules from Specified Directory Source: https://github.com/aniname/directory-import/blob/master/README.md Import modules from a specific directory path synchronously. Use this when modules are located in a subdirectory. ```javascript const { directoryImport } = require('directory-import'); /** * Import modules from the specified directory synchronously * @param {String} directoryPath - The path to the directory from which you want to import modules. * @returns {Object} An object containing all imported modules. */ const importedModules = directoryImport('./path/to/directory'); // { // '/sample-file-1.js': 'This is first sampleFile', // ... // } console.log(importedModules); ``` -------------------------------- ### Import Modules with Options and Callback Source: https://github.com/aniname/directory-import/blob/master/README.md Import modules using an options object and provide a callback function for per-module processing. This is the most flexible method for complex import scenarios. ```javascript const { directoryImport } = require('directory-import'); const options = { includeSubdirectories: true, targetDirectoryPath: './path/to/directory', importPattern: /\.js/, importMode: 'sync', limit: 2, }; /** * Import all modules from the specified directory and call the provided callback for each imported module. * @param {Object} targetDirectoryPath - options - The options object. * @param {Function} callback - The callback function to call for each imported module. * @returns {Object} An object containing all imported modules. */ directoryImport(options, (moduleName, modulePath, moduleData) => { // { // moduleName: 'sample-file-1', // modulePath: '/sample-file-1.js', // moduleData: 'This is first sampleFile' // } // ... console.info({ moduleName, modulePath, moduleData }); }); ``` -------------------------------- ### Import All Modules from a Directory Source: https://github.com/aniname/directory-import/blob/master/_autodocs/index.md Import all modules from a specified directory. This is the most basic usage. ```javascript const { directoryImport } = require('directory-import'); // Import all modules from a directory const modules = directoryImport('./src'); ``` -------------------------------- ### API Reference Features Source: https://github.com/aniname/directory-import/blob/master/_autodocs/REFERENCE-COVERAGE.md Highlights the features covered in the API reference documentation, including function signatures, parameter tables, return types, behavior explanations, usage examples, and error handling patterns. ```markdown ✓ **Function Documentation** (8/8 overloads) - Complete signature with parameter types - Parameter table (name, type, required, default, description) - Return type specification - Behavior explanation - Multiple usage examples - Error handling patterns - Integration examples ``` -------------------------------- ### Partial Import on Error Source: https://github.com/aniname/directory-import/blob/master/_autodocs/errors.md Handle errors during asynchronous imports by falling back to a synchronous import. This provides a way to get some modules even if the async import fails, though it might be less comprehensive. ```javascript const { directoryImport } = require('directory-import'); async function importWithPartialFailureHandling(directory) { try { return await directoryImport(directory, 'async'); } catch (error) { console.warn('Async import failed, falling back to sync:', error.message); try { return directoryImport(directory, 'sync'); } catch (syncError) { console.error('All import methods failed, returning empty object'); return {}; } } } const modules = await importWithPartialFailureHandling('./src'); ``` -------------------------------- ### Configuration Options Coverage Source: https://github.com/aniname/directory-import/blob/master/_autodocs/REFERENCE-COVERAGE.md Details the documentation status of configuration options, including their type, default values, and whether they are fully documented. All 6 options are covered. ```markdown | Option | Type | Default | Documented | |--------|------|---------|---| | `includeSubdirectories` | boolean | `true` | ✓ | | `targetDirectoryPath` | string | Caller dir | ✓ | | `importPattern` | RegExp | `/.*/ ` | ✓ | | `importMode` | string | `'sync'` | ✓ | | `limit` | number | `Infinity` | ✓ | | `forceReload` | boolean | `false` | ✓ | ``` -------------------------------- ### Async Import with Callback Source: https://github.com/aniname/directory-import/blob/master/_autodocs/index.md Perform an asynchronous import of modules from a directory, optionally providing a callback function to log loaded module information. ```javascript const { directoryImport } = require('directory-import'); const modules = await directoryImport('./src', 'async'); // Or with callback: const modules = await directoryImport('./src', 'async', (name, path, data, index) => { console.log(`Loaded: ${name}`); }); ``` -------------------------------- ### Configuration Module Loading with Filtering Source: https://github.com/aniname/directory-import/blob/master/_autodocs/api-reference/directoryImport.md Loads configuration modules from a directory, skipping hidden files (e.g., `.env`) and limiting the number of imports. It then merges all configurations into a single object. ```javascript const { directoryImport } = require('directory-import'); const configModules = directoryImport('./config', { importPattern: /^[^.].*\.js$/, limit: 20 }); const config = Object.values(configModules).reduce((acc, cfg) => { return { ...acc, ...cfg }; }, {}); ``` -------------------------------- ### Directory Import Architecture Diagram Source: https://github.com/aniname/directory-import/blob/master/_autodocs/api-reference/internal-modules.md Illustrates the architecture of the directory import process, showing the flow from the main entry point to internal modules and Node.js file system operations. ```text directoryImport() [index.ts, 8 overloads] ↓ preparePrivateOptions() [prepare-private-options.ts] ↓ importModules() [import-modules.ts] ↙ ↘ syncHandler() asyncHandler() ↓ ↓ readDirectorySync() readDirectoryAsync() ↓ ↓ fs.readdirSync() fs.readdir() + Promise.all() fs.statSync() fs.stat() ↓ ↓ importModule() [for each file path] ↓ require() ↓ ImportedModules object ``` -------------------------------- ### Synchronous Directory Import Source: https://github.com/aniname/directory-import/blob/master/README.md Use this snippet for a basic synchronous import of all modules in the calling directory. No arguments are needed. ```javascript const { directoryImport } = require('directory-import'); // Synchronously imports all modules in the same directory from which the code was called directoryImport(); ``` -------------------------------- ### Async/Await with Try-Catch Source: https://github.com/aniname/directory-import/blob/master/_autodocs/errors.md Use async/await with a try-catch block to handle potential errors during asynchronous directory imports. This pattern ensures that errors are caught and logged gracefully. ```javascript const { directoryImport } = require('directory-import'); async function loadModules() { try { const modules = await directoryImport('./src', 'async'); console.log('Import successful'); return modules; } catch (error) { console.error('Import failed:', error.message); throw error; } } loadModules().catch(console.error); ``` -------------------------------- ### Performance-Tuned Directory Import Source: https://github.com/aniname/directory-import/blob/master/_autodocs/configuration.md Optimize import performance by using asynchronous loading and a specific import pattern to skip hidden files. This is useful for large directories. ```javascript const { directoryImport } = require('directory-import'); const modules = directoryImport({ targetDirectoryPath: './src', importMode: 'async', importPattern: /^[^.].*\.(js|json)$/, // Skip hidden files limit: 1000, includeSubdirectories: true }); ``` -------------------------------- ### Directory Import with Callback Source: https://github.com/aniname/directory-import/blob/master/README.md Import modules from a specified directory and process each imported file using a callback function. The callback receives module details, and the final result is an object containing all imported modules. ```javascript const { directoryImport } = require('directory-import'); const importedModules = directoryImport('./path/to/directory', (moduleName, modulePath, moduleData) => { // { // moduleName: 'sample-file-1', // modulePath: '/sample-file-1.js', // moduleData: 'This is first sampleFile' // } // ... console.info({ moduleName, modulePath, moduleData }); }); // { // '/sample-file-1.js': 'This is first sampleFile', // ... // } console.info(importedModules); ``` -------------------------------- ### Import Modules from Current Directory Source: https://github.com/aniname/directory-import/blob/master/README.md Import all modules from the current directory synchronously. Useful for loading all available modules in the current scope. ```javascript const { directoryImport } = require('directory-import'); /** * Import modules from the current directory synchronously * @returns {Object} An object containing all imported modules. */ const importedModules = directoryImport(); // { // '/sample-file-1.js': 'This is first sampleFile', // ... // } console.log(importedModules); ``` -------------------------------- ### Async Directory Import with Options Object and Callback Source: https://github.com/aniname/directory-import/blob/master/_autodocs/api-reference/directoryImport.md Use this overload to import modules asynchronously from a specified directory using an options object and a callback function. The callback is executed for each module as it's loaded, and the function returns a Promise. ```javascript const { directoryImport } = require('directory-import'); const modules = directoryImport( { targetDirectoryPath: './src/routes', importMode: 'async', includeSubdirectories: true, limit: 50 }, (name, path, data, index) => { console.log(`[${index}] Route: ${name}`); } ); modules.then(loaded => { console.log(`Total routes: ${Object.keys(loaded).length}`); }); ``` -------------------------------- ### directoryImport(options, callback) Source: https://github.com/aniname/directory-import/blob/master/_autodocs/api-reference/directoryImport.md Imports modules using a configuration object and a callback function, allowing for detailed control over the import process and per-module processing. ```APIDOC ## directoryImport(options, callback) ### Description Imports modules using a configuration object and a callback function, allowing for detailed control over the import process and per-module processing. ### Method Not applicable (JavaScript function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None #### Function Parameters - **options** (ImportedModulesPublicOptions) - Required - Configuration object - **targetDirectoryPath** (string) - Required - Directory path - **importMode** ('sync' | 'async') - Optional - Import mode - **includeSubdirectories** (boolean) - Optional - Include subdirectories - **importPattern** (RegExp) - Optional - Pattern to match files - **limit** (number) - Optional - Maximum modules to import - **forceReload** (boolean) - Optional - Ignore Node.js require cache - **callback** (ImportModulesCallback) - Required - Function called for each imported module ### Request Example ```javascript const { directoryImport } = require('directory-import'); const modules = directoryImport( { targetDirectoryPath: './src/routes', importMode: 'async', includeSubdirectories: true, limit: 50 }, (name, path, data, index) => { console.log(`[${index}] Route: ${name}`); } ); modules.then(loaded => { console.log(`Total routes: ${Object.keys(loaded).length}`); }); ``` ### Response #### Success Response - **ImportedModules** (object) or **Promise** (Promise) - Depending on `options.importMode`. ``` -------------------------------- ### Import Modules with Callback (Current Directory) Source: https://github.com/aniname/directory-import/blob/master/_autodocs/api-reference/directoryImport.md Import modules from the current directory synchronously while processing each module with a provided callback function. The callback receives module name, path, data, and index. ```javascript const { directoryImport } = require('directory-import'); const modules = directoryImport((moduleName, modulePath, moduleData, index) => { console.log(`[${index}] ${moduleName} at ${modulePath}`); }); ``` -------------------------------- ### Limit Number of Modules Source: https://github.com/aniname/directory-import/blob/master/_autodocs/index.md Import modules from a directory, but limit the process to only the first specified number of modules found. ```javascript const { directoryImport } = require('directory-import'); // Load only first 10 modules const modules = directoryImport('./src', { limit: 10 }); ``` -------------------------------- ### Handle Common Patterns: Import with Limit and Error Details Source: https://github.com/aniname/directory-import/blob/master/_autodocs/errors.md Import modules with a specified limit and capture detailed error information if the import fails. This is useful for managing large imports and diagnosing specific issues. ```javascript const { directoryImport } = require('directory-import'); // Pattern: Import with limit and error details function importWithDetails(directory, limit = 50) { const modules = {}; const errors = []; try { return directoryImport(directory, { limit, importPattern: /\.(js|ts|json)$/ }); } catch (error) { // Attach error details for debugging return { modules, error: { message: error.message, code: error.code, path: error.path } }; } } ``` -------------------------------- ### Run Jest Tests Source: https://github.com/aniname/directory-import/blob/master/CONTRIBUTING.md Execute the test suite using npm. This command runs all tests defined within the project. ```bash npm run jest ``` -------------------------------- ### Import Modules with Mode (Sync/Async) Source: https://github.com/aniname/directory-import/blob/master/README.md Import modules from a specified directory, explicitly setting the import mode to 'sync' or 'async'. This provides control over the import operation's execution. ```javascript const { directoryImport } = require('directory-import'); /** * Import all modules from the specified directory synchronously or asynchronously. * @param {string} targetDirectoryPath - The path to the directory to import modules from. * @param {'sync'|'async'} mode - The import mode. Can be 'sync' or 'async'. * @returns {Object} An object containing all imported modules. */ const importModules = directoryImport('./path/to/directory', 'sync'); // { // '/sample-file-1.js': 'This is first sampleFile', // ... // } console.log(importedModules); ``` -------------------------------- ### Import Modules Synchronously or Asynchronously Source: https://github.com/aniname/directory-import/blob/master/_autodocs/api-reference/directoryImport.md Import modules from a specified directory using either synchronous or asynchronous mode. 'sync' returns the modules directly, while 'async' returns a Promise that resolves with the modules. ```javascript const { directoryImport } = require('directory-import'); // Synchronous const modules = directoryImport('./src/middleware', 'sync'); // Asynchronous const modulesPromise = directoryImport('./src/middleware', 'async'); modulesPromise.then(modules => { console.log('Modules loaded:', Object.keys(modules)); }); // With async/await const modules = await directoryImport('./src/middleware', 'async'); ``` -------------------------------- ### Import with Callback Function Source: https://github.com/aniname/directory-import/blob/master/_autodocs/index.md Import modules and provide a callback function to process each module during the import process. ```javascript // With callback directoryImport('./src', (name, path, data, index) => { console.log(`[${index}] ${name} at ${path}`); }); ``` -------------------------------- ### Configure Synchronous and Asynchronous Module Imports Source: https://github.com/aniname/directory-import/blob/master/_autodocs/configuration.md Use `importMode` to control whether modules are loaded synchronously, blocking the event loop, or asynchronously, returning a Promise. Synchronous mode is suitable for initialization, while asynchronous mode is preferred for non-blocking operations. ```javascript const { directoryImport } = require('directory-import'); // Synchronous (blocking) const modules = directoryImport('./src', { importMode: 'sync' }); console.log('Done immediately'); // Asynchronous (non-blocking) const promise = directoryImport('./src', { importMode: 'async' }); console.log('Returned immediately with Promise'); promise.then(modules => { console.log('Modules loaded asynchronously'); }); ``` -------------------------------- ### Synchronous Error Handling with Try-Catch Source: https://github.com/aniname/directory-import/blob/master/_autodocs/errors.md Illustrates a comprehensive synchronous error handling strategy using a try-catch block to manage various potential errors like 'ENOENT', invalid import modes, TypeErrors, and SyntaxErrors. ```javascript const { directoryImport } = require('directory-import'); try { const modules = directoryImport('./src'); console.log('Import successful'); } catch (error) { if (error.code === 'ENOENT') { console.error('Directory not found'); } else if (error.message.includes('sync or async')) { console.error('Invalid import mode'); } else if (error instanceof TypeError) { console.error('Invalid arguments:', error.message); } else if (error instanceof SyntaxError) { console.error('Syntax error in loaded module:', error.message); } else { console.error('Unknown error:', error); } } ``` -------------------------------- ### Asynchronous Directory Import Source: https://github.com/aniname/directory-import/blob/master/README.md Import files asynchronously from a specified directory. The result is a Promise that resolves with the imported modules. ```javascript const { directoryImport } = require('directory-import'); const result = directoryImport('./path/to/directory', 'async'); // Promise { } console.log(result); ``` -------------------------------- ### Sync Directory Import with Options Object Source: https://github.com/aniname/directory-import/blob/master/_autodocs/api-reference/directoryImport.md Use this overload to import modules synchronously from a specified directory using a detailed options object for fine-grained control over the import process. This is useful for complex import scenarios. ```javascript const { directoryImport } = require('directory-import'); const modules = directoryImport({ targetDirectoryPath: './src/plugins', importMode: 'sync', includeSubdirectories: true, importPattern: /plugin\.js$/, limit: 10, forceReload: false }); ``` -------------------------------- ### Directory Import - Async/Await Error Handling Source: https://github.com/aniname/directory-import/blob/master/_autodocs/api-reference/directoryImport.md Demonstrates error handling for directoryImport in asynchronous mode using async/await with a try-catch block. This provides a more synchronous-like error handling pattern. ```javascript const { directoryImport } = require('directory-import'); // With async/await try { const modules = await directoryImport('./src', 'async'); } catch (error) { console.error('Import failed:', error); } ``` -------------------------------- ### PreparePrivateOptions Function Signature Source: https://github.com/aniname/directory-import/blob/master/_autodocs/api-reference/internal-modules.md The `preparePrivateOptions` function normalizes and validates variadic arguments passed to the `directoryImport` function overloads, returning a standardized options object. ```typescript export default function preparePrivateOptions( ...arguments_: ImportModulesInputArguments ): ImportedModulesPrivateOptions ``` -------------------------------- ### Handle Common Patterns: Default Fallback Source: https://github.com/aniname/directory-import/blob/master/_autodocs/errors.md Import modules with a default fallback object if the specified directory is not found. This pattern ensures that the application can continue with default configurations. ```javascript const { directoryImport } = require('directory-import'); // Pattern: Import with default fallback function importOrDefault(directory, defaultModules = {}) { try { return directoryImport(directory); } catch (error) { if (error.code === 'ENOENT') { console.warn(`Directory not found, using defaults: ${directory}`); return defaultModules; } throw error; } } ``` -------------------------------- ### Directory Import - Asynchronous Error Handling Source: https://github.com/aniname/directory-import/blob/master/_autodocs/api-reference/directoryImport.md Illustrates asynchronous error handling for directoryImport using .catch() with Promises. It logs the error message upon rejection. ```javascript directoryImport('./src', 'async') .then(modules => { console.log('Imported:', Object.keys(modules)); }) .catch(error => { console.error('Import failed:', error.message); }); ``` -------------------------------- ### Import Modules with Options Object Source: https://github.com/aniname/directory-import/blob/master/README.md Import modules using a comprehensive options object for advanced configuration, including subdirectories, import patterns, mode, and limits. This offers fine-grained control over the import process. ```javascript const { directoryImport } = require('directory-import'); const options = { includeSubdirectories: true, targetDirectoryPath: './path/to/directory', importPattern: /\.js/, importMode: 'sync', limit: 2, }; /** * Import all modules from the specified directory * @param {Object} targetDirectoryPath - options - The options object. * @returns {Object} An object containing all imported modules. */ const importModules = directoryImport(options); // { // '/sample-file-1.js': 'This is first sampleFile', // ... // } console.log(importedModules); ``` -------------------------------- ### directoryImport(options) Source: https://github.com/aniname/directory-import/blob/master/_autodocs/api-reference/directoryImport.md Imports modules using a configuration object for fine-grained control over the import process, including directory path, import mode, and other advanced settings. ```APIDOC ## directoryImport(options) ### Description Imports modules using a configuration object for fine-grained control over the import process, including directory path, import mode, and other advanced settings. ### Method Not applicable (JavaScript function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None #### Function Parameters - **options** (ImportedModulesPublicOptions) - Required - Configuration object - **targetDirectoryPath** (string) - Required - Directory path - **importMode** ('sync' | 'async') - Optional - Import mode - **includeSubdirectories** (boolean) - Optional - Include subdirectories - **importPattern** (RegExp) - Optional - Pattern to match files - **limit** (number) - Optional - Maximum modules to import - **forceReload** (boolean) - Optional - Ignore Node.js require cache ### Request Example ```javascript const { directoryImport } = require('directory-import'); const modules = directoryImport({ targetDirectoryPath: './src/plugins', importMode: 'sync', includeSubdirectories: true, importPattern: /plugin\.js$/, limit: 10, forceReload: false }); ``` ### Response #### Success Response - **ImportedModules** (object) or **Promise** (Promise) - Depending on `options.importMode`. ``` -------------------------------- ### Error Recovery with Fallback Source: https://github.com/aniname/directory-import/blob/master/_autodocs/errors.md Implement a fallback mechanism to attempt importing from a default path if the primary path fails. This ensures that some modules are available even if the preferred source is unavailable. ```javascript const { directoryImport } = require('directory-import'); function importModulesWithFallback(primaryPath, fallbackPath = './src') { try { return directoryImport(primaryPath); } catch (error) { console.warn(`Failed to import from ${primaryPath}, falling back to ${fallbackPath}:`, error.message); try { return directoryImport(fallbackPath); } catch (fallbackError) { console.error('Both import paths failed:', fallbackError.message); return {}; } } } const modules = importModulesWithFallback('./custom', './default'); ``` -------------------------------- ### directoryImport(targetDirectoryPath, importMode, callback) Source: https://github.com/aniname/directory-import/blob/master/_autodocs/api-reference/directoryImport.md Imports modules from a specified directory path in either synchronous or asynchronous mode, with an optional callback function to process each imported module. ```APIDOC ## directoryImport(targetDirectoryPath, importMode, callback) ### Description Imports modules from a specified directory path in either synchronous or asynchronous mode, with an optional callback function to process each imported module. ### Method Not applicable (JavaScript function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None #### Function Parameters - **targetDirectoryPath** (string) - Required - Relative or absolute path to directory - **importMode** ('sync' | 'async') - Required - Import mode: 'sync' or 'async' - **callback** (ImportModulesCallback) - Required - Function called for each imported module ### Request Example ```javascript const { directoryImport } = require('directory-import'); // Async with callback const promise = directoryImport( './src/commands', 'async', (name, path, data, index) => { console.log(`Loaded command: ${name}`); } ); promise.then(modules => { console.log('All commands loaded'); }); ``` ### Response #### Success Response - **ImportedModules** (object) - If 'sync' mode is used. - **Promise** (Promise) - If 'async' mode is used. ```