1 | var path = require('path');
|
2 | var fs = require('fs');
|
3 |
|
4 | module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP;
|
5 |
|
6 | function mkdirP (p, mode, f, made) {
|
7 | if (typeof mode === 'function' || mode === undefined) {
|
8 | f = mode;
|
9 | mode = 0777 & (~process.umask());
|
10 | }
|
11 | if (!made) made = null;
|
12 |
|
13 | var cb = f || function () {};
|
14 | if (typeof mode === 'string') mode = parseInt(mode, 8);
|
15 | p = path.resolve(p);
|
16 |
|
17 | fs.mkdir(p, mode, function (er) {
|
18 | if (!er) {
|
19 | made = made || p;
|
20 | return cb(null, made);
|
21 | }
|
22 | switch (er.code) {
|
23 | case 'ENOENT':
|
24 | mkdirP(path.dirname(p), mode, function (er, made) {
|
25 | if (er) cb(er, made);
|
26 | else mkdirP(p, mode, cb, made);
|
27 | });
|
28 | break;
|
29 |
|
30 | case 'EEXIST':
|
31 | fs.stat(p, function (er2, stat) {
|
32 |
|
33 |
|
34 | if (er2 || !stat.isDirectory()) cb(er, made)
|
35 | else cb(null, made);
|
36 | });
|
37 | break;
|
38 |
|
39 | default:
|
40 | cb(er, made);
|
41 | break;
|
42 | }
|
43 | });
|
44 | }
|
45 |
|
46 | mkdirP.sync = function sync (p, mode, made) {
|
47 | if (mode === undefined) {
|
48 | mode = 0777 & (~process.umask());
|
49 | }
|
50 | if (!made) made = null;
|
51 |
|
52 | if (typeof mode === 'string') mode = parseInt(mode, 8);
|
53 | p = path.resolve(p);
|
54 |
|
55 | try {
|
56 | fs.mkdirSync(p, mode);
|
57 | made = made || p;
|
58 | }
|
59 | catch (err0) {
|
60 | switch (err0.code) {
|
61 | case 'ENOENT' :
|
62 | made = sync(path.dirname(p), mode, made);
|
63 | sync(p, mode, made);
|
64 | break;
|
65 |
|
66 | case 'EEXIST' :
|
67 | var stat;
|
68 | try {
|
69 | stat = fs.statSync(p);
|
70 | }
|
71 | catch (err1) {
|
72 | throw err0;
|
73 | }
|
74 | if (!stat.isDirectory()) throw err0;
|
75 | break;
|
76 | default :
|
77 | throw err0
|
78 | break;
|
79 | }
|
80 | }
|
81 |
|
82 | return made;
|
83 | };
|