0
# mkdirp
1
2
mkdirp provides recursive directory creation functionality, replicating the Unix `mkdir -p` command in Node.js environments. It offers both asynchronous (Promise-based) and synchronous APIs for creating nested directory structures, with automatic fallback between native Node.js fs.mkdir recursive implementation and a manual implementation for broader compatibility.
3
4
## Package Information
5
6
- **Package Name**: mkdirp
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install mkdirp`
10
11
## Core Imports
12
13
**Required Node.js Types**: `fs.MakeDirectoryOptions`, `fs.Stats`, `NodeJS.ErrnoException`
14
15
```typescript
16
// ESM - Named imports (no default export)
17
import { mkdirp, mkdirpSync } from "mkdirp";
18
// mkdirp is a function with properties attached via Object.assign
19
const result = await mkdirp("/path");
20
const resultSync = mkdirp.sync("/path"); // or mkdirpSync directly
21
22
// Additional named imports
23
import { mkdirpNative, mkdirpManual, useNative } from "mkdirp";
24
// Types are available through TypeScript's module system
25
import type { MkdirpOptions } from "mkdirp";
26
```
27
28
For CommonJS:
29
30
```javascript
31
// CommonJS - destructure named exports
32
const { mkdirp, mkdirpSync } = require("mkdirp");
33
// Or access all exports
34
const mkdirpLib = require("mkdirp");
35
const mkdirp = mkdirpLib.mkdirp;
36
```
37
38
## Basic Usage
39
40
```typescript
41
import { mkdirp, mkdirpSync } from "mkdirp";
42
43
// Async usage
44
const made = await mkdirp("/tmp/some/deep/path");
45
console.log(`Created directory: ${made}`); // First directory actually created
46
47
// Sync usage
48
const madeSync = mkdirpSync("/tmp/another/deep/path");
49
console.log(`Created directory: ${madeSync}`);
50
51
// With permissions
52
await mkdirp("/tmp/secure/path", { mode: 0o755 });
53
54
// With custom filesystem
55
await mkdirp("/tmp/custom/path", {
56
fs: {
57
mkdir: customMkdir,
58
stat: customStat
59
}
60
});
61
```
62
63
## Architecture
64
65
mkdirp is built around several key components:
66
67
- **Automatic Implementation Selection**: Chooses between native and manual based on Node.js version and options
68
- **Native Implementation**: Uses Node.js fs.mkdir with recursive option for optimal performance
69
- **Manual Implementation**: Creates directories one by one when native implementation is unavailable
70
- **Custom Filesystem Support**: Allows injection of custom fs operations via FsProvider interface
71
- **Cross-Platform Compatibility**: Handles Windows path restrictions and permissions properly
72
73
## Capabilities
74
75
### Primary Directory Creation
76
77
Core async directory creation function that automatically selects the best implementation. The mkdirp export is a function with attached utility methods via Object.assign.
78
79
```typescript { .api }
80
/**
81
* Creates directories recursively, like `mkdir -p`
82
* Named export with attached utility methods via Object.assign
83
*/
84
const mkdirp: {
85
(path: string, opts?: MkdirpOptions): Promise<string | undefined>;
86
mkdirpSync: typeof mkdirpSync;
87
mkdirpNative: typeof mkdirpNative;
88
mkdirpNativeSync: typeof mkdirpNativeSync;
89
mkdirpManual: typeof mkdirpManual;
90
mkdirpManualSync: typeof mkdirpManualSync;
91
sync: typeof mkdirpSync;
92
native: typeof mkdirpNative;
93
nativeSync: typeof mkdirpNativeSync;
94
manual: typeof mkdirpManual;
95
manualSync: typeof mkdirpManualSync;
96
useNative: typeof useNative;
97
useNativeSync: typeof useNativeSync;
98
};
99
100
/**
101
* Synchronous version of mkdirp
102
* @param path - The directory path to create
103
* @param opts - Options for directory creation
104
* @returns The first directory created, or undefined if already exists
105
*/
106
function mkdirpSync(path: string, opts?: MkdirpOptions): string | undefined;
107
```
108
109
### Implementation-Specific Functions
110
111
Functions that force specific implementation strategies.
112
113
```typescript { .api }
114
/**
115
* Creates directories using Node.js native fs.mkdir with recursive option
116
* Falls back to manual implementation on ENOENT errors
117
*/
118
function mkdirpNative(path: string, options?: MkdirpOptions): Promise<string | undefined>;
119
120
/**
121
* Synchronous version of mkdirpNative
122
*/
123
function mkdirpNativeSync(path: string, options?: MkdirpOptions): string | undefined;
124
125
/**
126
* Creates directories manually, one by one
127
* Used when native implementation is not available or fails
128
*/
129
function mkdirpManual(
130
path: string,
131
options?: MkdirpOptions,
132
made?: string | undefined
133
): Promise<string | undefined>;
134
135
/**
136
* Synchronous version of mkdirpManual
137
*/
138
function mkdirpManualSync(
139
path: string,
140
options?: MkdirpOptions,
141
made?: string | undefined
142
): string | undefined;
143
```
144
145
### Implementation Detection
146
147
Utilities to determine which implementation should be used.
148
149
```typescript { .api }
150
/**
151
* Determines if native implementation should be used
152
* Checks Node.js version and options compatibility
153
*/
154
function useNative(opts?: MkdirpOptions): boolean;
155
156
/**
157
* Synchronous version of useNative
158
*/
159
function useNativeSync(opts?: MkdirpOptions): boolean;
160
```
161
162
### Convenience Aliases
163
164
Alternative names for core functions.
165
166
```typescript { .api }
167
const sync: typeof mkdirpSync;
168
const manual: typeof mkdirpManual;
169
const manualSync: typeof mkdirpManualSync;
170
const native: typeof mkdirpNative;
171
const nativeSync: typeof mkdirpNativeSync;
172
```
173
174
## Types and Options
175
176
### MkdirpOptions
177
178
Configuration options for directory creation operations.
179
180
```typescript { .api }
181
/**
182
* Options for mkdirp operations
183
* Can be an options object, numeric mode, or string mode
184
*/
185
type MkdirpOptions = Options | number | string;
186
187
/**
188
* Base options interface
189
*/
190
interface Options extends FsProvider {
191
/** Directory permissions mode (default: 0o777) */
192
mode?: number | string;
193
/** Custom filesystem provider */
194
fs?: FsProvider;
195
/** Custom async mkdir function */
196
mkdirAsync?: (
197
path: string,
198
opts: MakeDirectoryOptions & { recursive?: boolean }
199
) => Promise<string | undefined>;
200
/** Custom async stat function */
201
statAsync?: (path: string) => Promise<Stats>;
202
}
203
204
/**
205
* Resolved options with all defaults applied
206
*/
207
interface MkdirpOptionsResolved {
208
mode: number;
209
fs: FsProvider;
210
mkdirAsync: (path: string, opts: MakeDirectoryOptions & { recursive?: boolean }) => Promise<string | undefined>;
211
statAsync: (path: string) => Promise<Stats>;
212
stat: (path: string, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => any) => any;
213
mkdir: (path: string, opts: MakeDirectoryOptions & { recursive?: boolean }, callback: (err: NodeJS.ErrnoException | null, made?: string) => any) => any;
214
statSync: (path: string) => Stats;
215
mkdirSync: (path: string, opts: MakeDirectoryOptions & { recursive?: boolean }) => string | undefined;
216
recursive?: boolean;
217
}
218
```
219
220
### FsProvider
221
222
Interface for custom filesystem implementations.
223
224
```typescript { .api }
225
/**
226
* Interface for providing custom filesystem operations
227
*/
228
interface FsProvider {
229
/** Custom stat function */
230
stat?: (
231
path: string,
232
callback: (err: NodeJS.ErrnoException | null, stats: Stats) => any
233
) => any;
234
/** Custom mkdir function */
235
mkdir?: (
236
path: string,
237
opts: MakeDirectoryOptions & { recursive?: boolean },
238
callback: (err: NodeJS.ErrnoException | null, made?: string) => any
239
) => any;
240
/** Custom statSync function */
241
statSync?: (path: string) => Stats;
242
/** Custom mkdirSync function */
243
mkdirSync?: (
244
path: string,
245
opts: MakeDirectoryOptions & { recursive?: boolean }
246
) => string | undefined;
247
}
248
```
249
250
### Internal Utility Functions
251
252
Internal utilities used by mkdirp implementations. Some of these are exported from their respective modules.
253
254
```typescript { .api }
255
/**
256
* Normalizes and resolves options with defaults
257
* @param opts - Raw options input
258
* @returns Resolved options object
259
*/
260
function optsArg(opts?: MkdirpOptions): MkdirpOptionsResolved;
261
262
/**
263
* Validates and resolves path arguments
264
* @param path - Path string to validate
265
* @returns Absolute path
266
* @throws TypeError for paths with null bytes
267
* @throws Error for illegal characters on Windows
268
*/
269
function pathArg(path: string): string;
270
271
```
272
273
### Directory Detection Utilities\n\nUtilities for finding the first directory that needs to be created during recursive mkdir operations. These are exported from the `find-made` module.\n\n```typescript { .api }\n/**\n * Finds the first directory that needs to be created (async)\n * @param opts - Resolved options object with fs methods\n * @param parent - Parent directory path to check\n * @param path - Target path being created\n * @returns Promise resolving to first directory to create, or undefined\n */\nfunction findMade(\n opts: MkdirpOptionsResolved,\n parent: string,\n path?: string\n): Promise<undefined | string>;\n\n/**\n * Synchronous version of findMade\n * @param opts - Resolved options object with fs methods\n * @param parent - Parent directory path to check \n * @param path - Target path being created\n * @returns First directory to create, or undefined\n */\nfunction findMadeSync(\n opts: MkdirpOptionsResolved,\n parent: string,\n path?: string\n): undefined | string;\n```\n\n## Command Line Interface
274
275
mkdirp includes a command-line tool for directory creation.
276
277
**Binary Path**: `./dist/cjs/src/bin.js` (configured in package.json `bin` field)
278
279
```bash
280
# Install globally to use CLI
281
npm install -g mkdirp
282
283
# Basic usage
284
mkdirp /path/to/create
285
286
# Multiple directories
287
mkdirp /path/one /path/two /path/three
288
289
# With permissions
290
mkdirp -m755 /path/to/create
291
mkdirp --mode=755 /path/to/create
292
293
# Print created directories
294
mkdirp -p /path/to/create
295
mkdirp --print /path/to/create
296
297
# Force manual implementation
298
mkdirp --manual /path/to/create
299
300
# Help and version
301
mkdirp --help
302
mkdirp --version
303
```
304
305
## Error Handling
306
307
mkdirp handles various filesystem error conditions:
308
309
- **ENOENT**: Missing parent directories - falls back to manual creation
310
- **EEXIST**: Directory already exists - returns undefined (not an error)
311
- **EROFS**: Read-only filesystem - returns undefined for existing directories
312
- **EISDIR**: Path exists as directory - returns undefined (success)
313
- **Path validation errors**: Throws TypeError for null bytes, Error for illegal Windows characters
314
- **Invalid options**: Throws TypeError for invalid options argument
315
316
## Usage Examples
317
318
### Basic Directory Creation
319
320
```typescript
321
import { mkdirp } from "mkdirp";
322
323
// Create nested directories
324
const created = await mkdirp("/tmp/foo/bar/baz");
325
if (created) {
326
console.log(`Created: ${created}`); // "/tmp/foo" if foo didn't exist
327
}
328
329
// Synchronous version
330
const createdSync = mkdirp.sync("/tmp/another/nested/path");
331
```
332
333
### Custom Permissions
334
335
```typescript
336
import { mkdirp } from "mkdirp";
337
338
// Using numeric mode
339
await mkdirp("/tmp/secure", 0o750);
340
341
// Using string mode
342
await mkdirp("/tmp/public", "755");
343
344
// Using options object
345
await mkdirp("/tmp/private", { mode: 0o700 });
346
```
347
348
### Custom Filesystem
349
350
```typescript
351
import { mkdirp } from "mkdirp";
352
import { promises as fs } from "fs";
353
354
const customFs = {
355
mkdir: fs.mkdir,
356
stat: fs.stat,
357
mkdirSync: require("fs").mkdirSync,
358
statSync: require("fs").statSync
359
};
360
361
await mkdirp("/custom/path", { fs: customFs });
362
```
363
364
### Implementation Selection
365
366
```typescript
367
import { mkdirp } from "mkdirp";
368
369
// Force native implementation
370
const native = await mkdirp.native("/tmp/native");
371
372
// Force manual implementation
373
const manual = await mkdirp.manual("/tmp/manual");
374
375
// Check which implementation would be used
376
const shouldUseNative = mkdirp.useNative({ mode: 0o755 });
377
console.log(`Using native: ${shouldUseNative}`);
378
```