UNPKG

2.67 kBJavaScriptView Raw
1(function () {
2 'use strict';
3
4 var fs = require('fs'),
5 mkdirOrig = fs.mkdir,
6 mkdirSyncOrig = fs.mkdirSync,
7 osSep = process.platform === 'win32' ? '\\' : '/';
8
9 /**
10 * Offers functionality similar to mkdir -p
11 *
12 * Asynchronous operation. No arguments other than a possible exception
13 * are given to the completion callback.
14 */
15 function mkdir_p (path, mode, callback, position) {
16 var parts = require('path').normalize(path).split(osSep);
17
18 mode = mode || process.umask();
19 position = position || 0;
20
21 if (position >= parts.length) {
22 return callback();
23 }
24
25 var directory = parts.slice(0, position + 1).join(osSep) || osSep;
26 fs.stat(directory, function(err) {
27 if (err === null) {
28 mkdir_p(path, mode, callback, position + 1);
29 } else {
30 mkdirOrig(directory, mode, function (err) {
31 if (err && err.errno != 17) {
32 return callback(err);
33 } else {
34 mkdir_p(path, mode, callback, position + 1);
35 }
36 });
37 }
38 });
39 }
40
41 function mkdirSync_p(path, mode, position) {
42 var parts = require('path').normalize(path).split(osSep);
43
44 mode = mode || process.umask();
45 position = position || 0;
46
47 if (position >= parts.length) {
48 return true;
49 }
50
51 var directory = parts.slice(0, position + 1).join(osSep) || osSep;
52 try {
53 fs.statSync(directory);
54 mkdirSync_p(path, mode, position + 1);
55 } catch (e) {
56 try {
57 mkdirSyncOrig(directory, mode);
58 mkdirSync_p(path, mode, position + 1);
59 } catch (e) {
60 if (e.errno != 17) {
61 throw e;
62 }
63 mkdirSync_p(path, mode, position + 1);
64 }
65 }
66 }
67
68 /**
69 * Polymorphic approach to fs.mkdir()
70 *
71 * If the third parameter is boolean and true assume that
72 * caller wants recursive operation.
73 */
74 fs.mkdir = function (path, mode, recursive, callback) {
75 if (typeof recursive !== 'boolean') {
76 callback = recursive;
77 recursive = false;
78 }
79
80 if (typeof callback !== 'function') {
81 callback = function () {};
82 }
83
84 if (!recursive) {
85 mkdirOrig(path, mode, callback);
86 } else {
87 mkdir_p(path, mode, callback);
88 }
89 }
90
91 /**
92 * Polymorphic approach to fs.mkdirSync()
93 *
94 * If the third parameter is boolean and true assume that
95 * caller wants recursive operation.
96 */
97 fs.mkdirSync = function (path, mode, recursive) {
98 if (typeof recursive !== 'boolean') {
99 recursive = false;
100 }
101
102 if (!recursive) {
103 mkdirSyncOrig(path, mode);
104 } else {
105 mkdirSync_p(path, mode);
106 }
107 }
108
109 module.exports = fs;
110}());