-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfileSystem.js
More file actions
109 lines (96 loc) · 2.87 KB
/
fileSystem.js
File metadata and controls
109 lines (96 loc) · 2.87 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
const fs = require('fs');
const os = require('os');
/**
* Searches all file paths by given extension
* @param {String} directoryPath - path to directory opened in console
* @param {String} extension - extension of the file to search
* @param {Array} filePaths - array to store found paths
* @param {Array} ignore - array of path masks to be ignored
* @return {Array}
*/
function getAllFilePathsWithExtension(directoryPath, extension, filePaths, ignore) {
filePaths = filePaths || [];
const fileNames = fs.readdirSync(directoryPath);
for (const fileName of fileNames) {
const filePath = directoryPath + '/' + fileName;
let ignored = false;
for (const prohibited of ignore) {
let mask = directoryPath.replace(/[\[\^\$\+\(\)\.]/g,
(symbol) => {
return '\\' + symbol;
});
mask = new RegExp(mask + ".*/" + prohibited + '$');
if (mask.test(filePath)) {
ignored = true;
break;
}
}
if (ignored) {
continue;
}
if (fs.statSync(filePath).isDirectory()) {
getAllFilePathsWithExtension(filePath, extension, filePaths, ignore);
} else if (filePath.endsWith(`.${extension}`)) {
filePaths.push(filePath);
}
}
return filePaths;
}
/**
* Reads file
* @param {String} filePath - paths to the file in file system
* @return {String}
*/
function readFile(filePath) {
return fs.readFileSync(filePath, 'utf8');
}
/**
* Converts relative path into absolute one
* @param {String} path - relative path
* @return {String|Null} - converted path or null if path is invalid
*/
function absolute(path) {
if (os.platform() == 'win32' && path.indexOf(':') != -1 || os.platform() != 'win32' && path[0] == '/') {
path = path.replace(/\\/g, '/');
} else {
path = (process.cwd() + '/' + path).replace(/\\/g, '/');
}
let upper = path.indexOf('../');
while (upper != -1) {
if (upper < 3 || path[upper - 2] == ':') {
return null;
}
let previous = path.lastIndexOf('/', upper - 2);
path = path.slice(0, previous + 1) + path.slice(upper + 3);
upper = path.indexOf('../');
}
if (!fs.existsSync(path)) {
path = null;
}
return path;
}
/**
* Saves information about file
* @prop {String} content - content of the file
* @prop {String} path - path to the file
*/
class File {
/**
* @constructor
* @param {String} path - path to file in OS
*/
constructor(path) {
this.path = path;
}
/**
* Gets and saves content from the file into class instance
*/
readin () {
this.content = readFile(this.path);
}
}
module.exports = {
File,
getAllFilePathsWithExtension,
absolute
};