or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

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

0

# require-all

1

2

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.

3

4

## Package Information

5

6

- **Package Name**: require-all

7

- **Package Type**: npm

8

- **Language**: JavaScript

9

- **Installation**: `npm install require-all`

10

11

## Core Imports

12

13

```javascript

14

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

15

```

16

17

## Basic Usage

18

19

```javascript

20

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

21

22

// Simple usage - require all .js and .json files from a directory

23

const modules = requireAll(__dirname + '/lib');

24

25

// Advanced usage with configuration

26

const controllers = requireAll({

27

dirname: __dirname + '/controllers',

28

filter: /(.+Controller)\.js$/,

29

excludeDirs: /^\.(git|svn)$/,

30

recursive: true

31

});

32

33

// Result structure:

34

// {

35

// HomeController: { ... }, // contents of HomeController.js

36

// UserController: { ... }, // contents of UserController.js

37

// // ... other controller modules

38

// }

39

```

40

41

## Capabilities

42

43

### Main Function

44

45

The primary export that requires all files from a directory based on provided options.

46

47

```javascript { .api }

48

/**

49

* Require all files from a directory with flexible configuration options

50

* @param {string|object} options - Directory path as string, or configuration object

51

* @returns {object} Object containing all required modules mapped to property names

52

*/

53

function requireAll(options);

54

```

55

56

**Simple String Usage:**

57

```javascript

58

const modules = requireAll('/path/to/directory');

59

```

60

61

**Advanced Object Configuration:**

62

```javascript

63

const modules = requireAll({

64

dirname: '/path/to/directory',

65

filter: /(.+Controller)\.js$/,

66

excludeDirs: /^\.(git|svn)$/,

67

recursive: true,

68

resolve: function(module) { return new module(); },

69

map: function(name, filepath) { return name.toLowerCase(); }

70

});

71

```

72

73

### Configuration Options

74

75

When using the object configuration format, the following options are available:

76

77

```javascript { .api }

78

interface RequireAllOptions {

79

/** Path to the directory to require files from (required) */

80

dirname: string;

81

82

/** Filter to determine which files to require and how to name them */

83

filter?: RegExp | ((filename: string) => string | undefined);

84

85

/** Pattern to exclude directories from recursive traversal */

86

excludeDirs?: RegExp | boolean;

87

88

/** Whether to recursively traverse subdirectories */

89

recursive?: boolean;

90

91

/** Function to transform required modules (e.g., instantiate constructors) */

92

resolve?: (module: any) => any;

93

94

/** Function to transform file/directory names to property names */

95

map?: (name: string, filepath: string) => string;

96

}

97

```

98

99

#### dirname

100

- **Type**: `string`

101

- **Required**: Yes

102

- **Description**: Path to the directory to require files from

103

104

#### filter

105

- **Type**: `RegExp | Function`

106

- **Default**: `/^([^\.].*)\.js(on)?$/` (matches .js and .json files, excluding hidden files)

107

- **Description**: Determines which files to require and extracts property names

108

- **RegExp**: Uses capture groups to extract property names. If no capture group, uses full match

109

- **Function**: `(filename: string) => string | falsy` - return falsy to ignore file, string to use as property name

110

111

**Filter Examples:**

112

```javascript

113

// Only require files ending in "Controller.js", use captured name

114

filter: /(.+Controller)\.js$/

115

116

// Custom function filter

117

filter: function(fileName) {

118

const parts = fileName.split('-');

119

if (parts[1] !== 'Controller.js') return;

120

return parts[0]; // Use first part as property name

121

}

122

```

123

124

#### excludeDirs

125

- **Type**: `RegExp | boolean`

126

- **Default**: `/^\./` (excludes hidden directories)

127

- **Description**: Pattern to exclude directories from recursive traversal

128

- **Set to `false`** to disable directory exclusion entirely

129

130

#### recursive

131

- **Type**: `boolean`

132

- **Default**: `true`

133

- **Description**: Whether to recursively traverse subdirectories

134

135

#### resolve

136

- **Type**: `Function`

137

- **Default**: Identity function (returns input unchanged)

138

- **Description**: Function to transform required modules

139

- **Function signature**: `(module: any) => any`

140

141

**Resolve Examples:**

142

```javascript

143

// Instantiate constructor functions

144

resolve: function(Constructor) {

145

return new Constructor();

146

}

147

148

// Call function with arguments

149

resolve: function(fn) {

150

return fn('arg1', 'arg2');

151

}

152

```

153

154

#### map

155

- **Type**: `Function`

156

- **Default**: Identity function (returns input unchanged)

157

- **Description**: Function to transform file/directory names to property names

158

- **Function signature**: `(name: string, filepath: string) => string`

159

160

**Map Examples:**

161

```javascript

162

// Convert snake_case to camelCase

163

map: function(name, path) {

164

return name.replace(/_([a-z])/g, function(m, c) {

165

return c.toUpperCase();

166

});

167

}

168

169

// Convert dashes to underscores

170

map: function(name, path) {

171

return name.replace(/-([A-Za-z])/, function(m, c) {

172

return '_' + c.toLowerCase();

173

});

174

}

175

```

176

177

## Return Value Structure

178

179

The function returns an object where:

180

- **Keys** are property names derived from file/directory names (processed through `filter` and `map`)

181

- **Values** are the required modules (potentially transformed via `resolve`)

182

- **Nested directories** create nested object structures

183

- **Empty directories** are excluded from results

184

185

**Example directory structure:**

186

```

187

controllers/

188

├── HomeController.js // exports { index: 1, show: 2 }

189

├── UserController.js // exports { create: 3, update: 4 }

190

└── admin/

191

└── AdminController.js // exports { dashboard: 5 }

192

```

193

194

**Resulting object:**

195

```javascript

196

{

197

HomeController: { index: 1, show: 2 },

198

UserController: { create: 3, update: 4 },

199

admin: {

200

AdminController: { dashboard: 5 }

201

}

202

}

203

```

204

205

## Usage Examples

206

207

### Constructor Instantiation

208

Automatically instantiate exported constructor functions:

209

210

```javascript

211

const controllers = requireAll({

212

dirname: __dirname + '/controllers',

213

filter: /(.+Controller)\.js$/,

214

resolve: function(Controller) {

215

return new Controller();

216

}

217

});

218

```

219

220

### Property Name Transformation

221

Transform file names to desired property names:

222

223

```javascript

224

const controllers = requireAll({

225

dirname: __dirname + '/controllers',

226

filter: /(.+Controller)\.js$/,

227

map: function(name, path) {

228

// Convert "main-Controller" to "mainController"

229

return name.replace(/-([A-Z])/, function(m, c) {

230

return c.toLowerCase();

231

});

232

}

233

});

234

```

235

236

### Custom File Filtering

237

Use a function to implement complex filtering logic:

238

239

```javascript

240

const modules = requireAll({

241

dirname: __dirname + '/modules',

242

filter: function(fileName) {

243

// Only require files with specific naming pattern

244

const parts = fileName.split('-');

245

if (parts.length !== 2 || parts[1] !== 'module.js') {

246

return; // Skip this file

247

}

248

return parts[0]; // Use first part as property name

249

}

250

});

251

```

252

253

### Directory Exclusion

254

Control which directories to exclude from traversal:

255

256

```javascript

257

// Exclude .git and .svn directories

258

const modules = requireAll({

259

dirname: __dirname + '/src',

260

excludeDirs: /^\.(git|svn)$/

261

});

262

263

// Include all directories (disable exclusion)

264

const modules = requireAll({

265

dirname: __dirname + '/src',

266

excludeDirs: false

267

});

268

```

269

270

## Error Handling

271

272

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

273

274

- **Non-existent directories**: `ENOENT` error when `dirname` doesn't exist

275

- **Permission issues**: `EACCES` error when lacking read permissions

276

- **Invalid file paths**: Various filesystem errors for malformed paths

277

- **Module loading errors**: Any errors thrown by required files will propagate

278

279

**Error handling example:**

280

```javascript

281

try {

282

const modules = requireAll({

283

dirname: __dirname + '/controllers'

284

});

285

} catch (error) {

286

if (error.code === 'ENOENT') {

287

console.error('Controllers directory not found');

288

} else {

289

console.error('Error loading modules:', error.message);

290

}

291

}

292

```