file.js
7.48 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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
/*
* Utilities: A classic collection of JavaScript utilities
* Copyright 2112 Matthew Eernisse (mde@fleegix.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
let fs = require('fs');
let path = require('path');
/**
@name file
@namespace file
*/
let fileUtils = new (function () {
// Recursively copy files and directories
let _copyFile = function (fromPath, toPath, opts) {
let from = path.normalize(fromPath)
let to = path.normalize(toPath)
let options = opts || {}
let fromStat;
let toStat;
let destExists;
let destDoesNotExistErr;
let content;
let filename;
let dirContents;
let targetDir;
fromStat = fs.statSync(from);
try {
//console.dir(to + ' destExists');
toStat = fs.statSync(to);
destExists = true;
}
catch(e) {
//console.dir(to + ' does not exist');
destDoesNotExistErr = e;
destExists = false;
}
// Destination dir or file exists, copy into (directory)
// or overwrite (file)
if (destExists) {
// If there's a rename-via-copy file/dir name passed, use it.
// Otherwise use the actual file/dir name
filename = options.rename || path.basename(from);
// Copying a directory
if (fromStat.isDirectory()) {
dirContents = fs.readdirSync(from);
targetDir = path.join(to, filename);
// We don't care if the target dir already exists
try {
fs.mkdirSync(targetDir, {mode: fromStat.mode & 0o777});
}
catch(e) {
if (e.code !== 'EEXIST') {
throw e;
}
}
for (let i = 0, ii = dirContents.length; i < ii; i++) {
_copyFile(path.join(from, dirContents[i]), targetDir, {preserveMode: options.preserveMode});
}
}
// Copying a file
else {
content = fs.readFileSync(from);
let mode = fromStat.mode & 0o777;
let targetFile = to;
if (toStat.isDirectory()) {
targetFile = path.join(to, filename);
}
let fileExists = fs.existsSync(targetFile);
fs.writeFileSync(targetFile, content);
// If the file didn't already exist, use the original file mode.
// Otherwise, only update the mode if preserverMode is true.
if(!fileExists || options.preserveMode) {
fs.chmodSync(targetFile, mode);
}
}
}
// Dest doesn't exist, can't create it
else {
throw destDoesNotExistErr;
}
};
// Remove the given directory
let _rmDir = function (dirPath) {
let dir = path.normalize(dirPath);
let paths = [];
paths = fs.readdirSync(dir);
paths.forEach(function (p) {
let curr = path.join(dir, p);
let stat = fs.lstatSync(curr);
if (stat.isDirectory()) {
_rmDir(curr);
}
else {
try {
fs.unlinkSync(curr);
} catch(e) {
if (e.code === 'EPERM') {
fs.chmodSync(curr, parseInt(666, 8));
fs.unlinkSync(curr);
} else {
throw e;
}
}
}
});
fs.rmdirSync(dir);
};
/**
@name file#cpR
@public
@function
@description Copies a directory/file to a destination
@param {String} fromPath The source path to copy from
@param {String} toPath The destination path to copy to
@param {Object} opts Options to use
@param {Boolean} [opts.preserveMode] If target file already exists, this
determines whether the original file's mode is copied over. The default of
false mimics the behavior of the `cp` command line tool. (Default: false)
*/
this.cpR = function (fromPath, toPath, options) {
let from = path.normalize(fromPath);
let to = path.normalize(toPath);
let toStat;
let doesNotExistErr;
let filename;
let opts = options || {};
if (from == to) {
throw new Error('Cannot copy ' + from + ' to itself.');
}
// Handle rename-via-copy
try {
toStat = fs.statSync(to);
}
catch(e) {
doesNotExistErr = e;
// Get abs path so it's possible to check parent dir
if (!this.isAbsolute(to)) {
to = path.join(process.cwd(), to);
}
// Save the file/dir name
filename = path.basename(to);
// See if a parent dir exists, so there's a place to put the
/// renamed file/dir (resets the destination for the copy)
to = path.dirname(to);
try {
toStat = fs.statSync(to);
}
catch(e) {}
if (toStat && toStat.isDirectory()) {
// Set the rename opt to pass to the copy func, will be used
// as the new file/dir name
opts.rename = filename;
//console.log('filename ' + filename);
}
else {
throw doesNotExistErr;
}
}
_copyFile(from, to, opts);
};
/**
@name file#mkdirP
@public
@function
@description Create the given directory(ies) using the given mode permissions
@param {String} dir The directory to create
@param {Number} mode The mode to give the created directory(ies)(Default: 0755)
*/
this.mkdirP = function (dir, mode) {
let dirPath = path.normalize(dir);
let paths = dirPath.split(/\/|\\/);
let currPath = '';
let next;
if (paths[0] == '' || /^[A-Za-z]+:/.test(paths[0])) {
currPath = paths.shift() || '/';
currPath = path.join(currPath, paths.shift());
//console.log('basedir');
}
while ((next = paths.shift())) {
if (next == '..') {
currPath = path.join(currPath, next);
continue;
}
currPath = path.join(currPath, next);
try {
//console.log('making ' + currPath);
fs.mkdirSync(currPath, mode || parseInt(755, 8));
}
catch(e) {
if (e.code != 'EEXIST') {
throw e;
}
}
}
};
/**
@name file#rmRf
@public
@function
@description Deletes the given directory/file
@param {String} p The path to delete, can be a directory or file
*/
this.rmRf = function (p, options) {
let stat;
try {
stat = fs.lstatSync(p);
if (stat.isDirectory()) {
_rmDir(p);
}
else {
fs.unlinkSync(p);
}
}
catch (e) {}
};
/**
@name file#isAbsolute
@public
@function
@return {Boolean/String} If it's absolute the first character is returned otherwise false
@description Checks if a given path is absolute or relative
@param {String} p Path to check
*/
this.isAbsolute = function (p) {
let match = /^[A-Za-z]+:\\|^\//.exec(p);
if (match && match.length) {
return match[0];
}
return false;
};
/**
@name file#absolutize
@public
@function
@return {String} Returns the absolute path for the given path
@description Returns the absolute path for the given path
@param {String} p The path to get the absolute path for
*/
this.absolutize = function (p) {
if (this.isAbsolute(p)) {
return p;
}
else {
return path.join(process.cwd(), p);
}
};
})();
module.exports = fileUtils;