mkdir.js
2.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
var common = require('./common');
var fs = require('fs');
var path = require('path');
common.register('mkdir', _mkdir, {
cmdOptions: {
'p': 'fullpath',
},
});
// Recursively creates 'dir'
function mkdirSyncRecursive(dir) {
var baseDir = path.dirname(dir);
// Prevents some potential problems arising from malformed UNCs or
// insufficient permissions.
/* istanbul ignore next */
if (baseDir === dir) {
common.error('dirname() failed: [' + dir + ']');
}
// Base dir exists, no recursion necessary
if (fs.existsSync(baseDir)) {
fs.mkdirSync(dir, parseInt('0777', 8));
return;
}
// Base dir does not exist, go recursive
mkdirSyncRecursive(baseDir);
// Base dir created, can create dir
fs.mkdirSync(dir, parseInt('0777', 8));
}
//@
//@ ### mkdir([options,] dir [, dir ...])
//@ ### mkdir([options,] dir_array)
//@ Available options:
//@
//@ + `-p`: full path (will create intermediate dirs if necessary)
//@
//@ Examples:
//@
//@ ```javascript
//@ mkdir('-p', '/tmp/a/b/c/d', '/tmp/e/f/g');
//@ mkdir('-p', ['/tmp/a/b/c/d', '/tmp/e/f/g']); // same as above
//@ ```
//@
//@ Creates directories.
function _mkdir(options, dirs) {
if (!dirs) common.error('no paths given');
if (typeof dirs === 'string') {
dirs = [].slice.call(arguments, 1);
}
// if it's array leave it as it is
dirs.forEach(function (dir) {
try {
var stat = fs.lstatSync(dir);
if (!options.fullpath) {
common.error('path already exists: ' + dir, { continue: true });
} else if (stat.isFile()) {
common.error('cannot create directory ' + dir + ': File exists', { continue: true });
}
return; // skip dir
} catch (e) {
// do nothing
}
// Base dir does not exist, and no -p option given
var baseDir = path.dirname(dir);
if (!fs.existsSync(baseDir) && !options.fullpath) {
common.error('no such file or directory: ' + baseDir, { continue: true });
return; // skip dir
}
try {
if (options.fullpath) {
mkdirSyncRecursive(path.resolve(dir));
} else {
fs.mkdirSync(dir, parseInt('0777', 8));
}
} catch (e) {
var reason;
if (e.code === 'EACCES') {
reason = 'Permission denied';
} else if (e.code === 'ENOTDIR' || e.code === 'ENOENT') {
reason = 'Not a directory';
} else {
/* istanbul ignore next */
throw e;
}
common.error('cannot create directory ' + dir + ': ' + reason, { continue: true });
}
});
return '';
} // mkdir
module.exports = _mkdir;