Recursively iterates over specified directory, require()'ing each file, and returning a nested hash structure containing those modules.
npx @tessl/cli install tessl/npm-require-directory@2.1.00
# require-directory
1
2
Recursively iterates over specified directory, `require()`ing each file, and returning a nested hash structure containing those modules. Enables automatic loading and organizing of multiple modules from a directory hierarchy without manually requiring each file.
3
4
## Package Information
5
6
- **Package Name**: require-directory
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install require-directory`
10
11
## Core Imports
12
13
```javascript { .api }
14
const requireDirectory = require('require-directory');
15
```
16
17
## Basic Usage
18
19
```javascript
20
const requireDirectory = require('require-directory');
21
22
// Require all files from current directory
23
const modules = requireDirectory(module);
24
25
// Require all files from a specific directory
26
const routes = requireDirectory(module, './routes');
27
28
// With options - only JavaScript files, no recursion
29
const controllers = requireDirectory(module, './controllers', {
30
extensions: ['js'],
31
recurse: false
32
});
33
```
34
35
## Capabilities
36
37
### Directory Requiring
38
39
Recursively processes a directory structure, requiring each file and building a nested hash structure that mirrors the directory layout.
40
41
```javascript { .api }
42
/**
43
* Recursively requires all files in a directory and returns nested hash structure
44
* @param {Object} module - The module object (typically 'module')
45
* @param {string} [path] - Path to directory (defaults to module's directory)
46
* @param {Object} [options] - Configuration options
47
* @returns {Object} Nested hash structure containing required modules
48
*/
49
function requireDirectory(module, path, options);
50
```
51
52
**Parameters:**
53
- `module` (required): The module object, typically pass `module`
54
- `path` (optional): String path to directory to require from. If omitted, uses the directory containing the calling module
55
- `options` (optional): Configuration object for controlling behavior
56
57
**Returns:** Object containing nested hash structure where:
58
- File modules are keyed by filename (without extension)
59
- Directory modules are keyed by directory name
60
- Structure mirrors the filesystem hierarchy
61
62
### Configuration Options
63
64
Control file processing, filtering, and transformation behavior.
65
66
```javascript { .api }
67
interface RequireDirectoryOptions {
68
/** Array of file extensions to process */
69
extensions?: string[];
70
/** Whether to recursively process subdirectories */
71
recurse?: boolean;
72
/** Function to transform object keys */
73
rename?: (name: string, joined: string, filename: string) => string;
74
/** Function to transform loaded modules - return value used if truthy, otherwise original object */
75
visit?: (obj: any, joined: string, filename: string) => any;
76
/** RegExp or function to whitelist files */
77
include?: RegExp | ((path: string, filename: string) => boolean);
78
/** RegExp or function to blacklist files */
79
exclude?: RegExp | ((path: string, filename: string) => boolean);
80
}
81
```
82
83
**Option Details:**
84
85
- **`extensions`**: Array of file extensions to include (default: `['js', 'json', 'coffee']`)
86
- **`recurse`**: Boolean controlling recursive directory processing (default: `true`)
87
- **`rename`**: Function to transform object keys, receives `(name, joined, filename)`
88
- **`visit`**: Function to transform loaded modules, receives `(obj, joined, filename)`. Return value is used if truthy, otherwise original object is kept
89
- **`include`**: RegExp or function to whitelist specific files
90
- **`exclude`**: RegExp or function to blacklist specific files
91
92
**Usage Examples:**
93
94
```javascript
95
// Custom extensions
96
const modules = requireDirectory(module, './lib', {
97
extensions: ['js', 'ts']
98
});
99
100
// No recursion
101
const topLevel = requireDirectory(module, './routes', {
102
recurse: false
103
});
104
105
// File filtering with RegExp
106
const jsOnly = requireDirectory(module, './src', {
107
include: /\.js$/
108
});
109
110
// File filtering with function
111
const filtered = requireDirectory(module, './controllers', {
112
exclude: (path, filename) => filename.startsWith('test')
113
});
114
115
// Key transformation
116
const uppercased = requireDirectory(module, './models', {
117
rename: (name) => name.toUpperCase()
118
});
119
120
// Module transformation
121
const wrapped = requireDirectory(module, './middleware', {
122
visit: (obj) => {
123
// Wrap functions with logging
124
if (typeof obj === 'function') {
125
return (...args) => {
126
console.log('Calling:', obj.name);
127
return obj(...args);
128
};
129
}
130
return obj;
131
}
132
});
133
```
134
135
### Default Options Access
136
137
Access the default configuration object used by requireDirectory.
138
139
```javascript { .api }
140
/**
141
* Default options object used by requireDirectory
142
*/
143
const defaults: RequireDirectoryOptions;
144
```
145
146
The defaults object contains:
147
148
```javascript { .api }
149
const defaults = {
150
extensions: ['js', 'json', 'coffee'],
151
recurse: true,
152
rename: function(name) { return name; },
153
visit: function(obj) { return obj; }
154
};
155
```
156
157
**Usage:**
158
159
```javascript
160
// Access default options
161
const defaultOpts = requireDirectory.defaults;
162
163
// Modify defaults for all subsequent calls
164
requireDirectory.defaults.extensions = ['js', 'ts'];
165
```
166
167
## Types
168
169
```javascript { .api }
170
/**
171
* Configuration options for requireDirectory function
172
*/
173
interface RequireDirectoryOptions {
174
/** File extensions to process (default: ['js', 'json', 'coffee']) */
175
extensions?: string[];
176
/** Enable recursive directory processing (default: true) */
177
recurse?: boolean;
178
/** Transform function for object keys */
179
rename?: (name: string, joined: string, filename: string) => string;
180
/** Transform function for loaded modules */
181
visit?: (obj: any, joined: string, filename: string) => any;
182
/** RegExp pattern or function to include specific files */
183
include?: RegExp | ((path: string, filename: string) => boolean);
184
/** RegExp pattern or function to exclude specific files */
185
exclude?: RegExp | ((path: string, filename: string) => boolean);
186
}
187
188
/**
189
* Filter function signature for include/exclude options
190
*/
191
type FilterFunction = (path: string, filename: string) => boolean;
192
193
/**
194
* Rename function signature for transforming object keys
195
*/
196
type RenameFunction = (name: string, joined: string, filename: string) => string;
197
198
/**
199
* Visit function signature for transforming loaded modules
200
* Return value is used if truthy, otherwise original object is kept
201
*/
202
type VisitFunction = (obj: any, joined: string, filename: string) => any;
203
```
204
205
## Behavior Notes
206
207
- **Self-exclusion**: The calling module file is automatically excluded from results
208
- **Empty directories**: Directories containing no matching files are excluded from results
209
- **Key generation**: Object keys are generated by removing file extensions from filenames
210
- **Module loading**: Uses `module.require()` internally for proper relative path resolution
211
- **Error handling**: File system and module loading errors are not caught and will propagate
212
- **Path resolution**: Relative paths are resolved relative to the calling module's directory
213
214
## Common Patterns
215
216
```javascript
217
// Route organization pattern
218
// routes/index.js
219
module.exports = requireDirectory(module);
220
221
// app.js
222
const routes = require('./routes');
223
app.get('/', routes.home);
224
app.get('/users', routes.users.list);
225
226
// Controller loading with transformation
227
const controllers = requireDirectory(module, './controllers', {
228
visit: (controller) => {
229
// Auto-bind methods to controller instance
230
if (typeof controller === 'object') {
231
Object.getOwnPropertyNames(Object.getPrototypeOf(controller))
232
.filter(name => typeof controller[name] === 'function')
233
.forEach(name => controller[name] = controller[name].bind(controller));
234
}
235
return controller;
236
}
237
});
238
239
// Development vs production file loading
240
const middleware = requireDirectory(module, './middleware', {
241
exclude: process.env.NODE_ENV === 'production' ? /dev\.js$/ : /prod\.js$/
242
});
243
```