-
Notifications
You must be signed in to change notification settings - Fork 809
/
File.js
116 lines (95 loc) · 2.25 KB
/
File.js
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
let fs = require('fs');
let path = require('path');
let uglify = require('uglify-js');
let UglifyCss = require('clean-css');
class File {
/**
* Create a new File instance.
*
* @param {string} file
*/
constructor(file) {
this.file = file;
this.fileType = path.parse(file).ext;
}
/**
* Static constructor.
*
* @param {string} file
*/
static find(file) {
return new File(file);
}
/**
* Minify the file, if it is CSS or JS.
*/
minify() {
if (this.fileType === '.js') {
this.write(uglify.minify(this.file).code);
}
if (this.fileType === '.css') {
this.write(
new UglifyCss().minify(this.read()).styles
);
}
}
/**
* Determine if the given file exists.
*
* @param {string} file
*/
static exists(file) {
return fs.existsSync(file);
}
/**
* Read the file.
*/
read() {
return fs.readFileSync(this.file, {
encoding: 'utf-8'
});
}
/**
* Write the given contents to the file.
*
* @param {string} body
*/
write(body) {
fs.writeFileSync(this.file, body);
return this;
}
/**
* Delete/Unlink the current file.
*/
delete() {
if (fs.existsSync(this.file)) {
fs.unlinkSync(this.file);
}
}
/**
* Fetch the full path to the file.
*
* @return {string}
*/
path() {
return path.resolve(this.file);
}
/**
* Parse the file path into segments.
*/
parsePath() {
let outputSegments = path.parse(this.file);
return {
path: this.file,
pathWithoutExt: path.join(outputSegments.dir, `${outputSegments.name}`),
hashedPath: path.join(outputSegments.dir, `${outputSegments.name}.[hash]${outputSegments.ext}`),
base: outputSegments.dir,
file: outputSegments.base,
hashedFile: `${outputSegments.name}.[hash]${outputSegments.ext}`,
name: outputSegments.name,
isDir: ! outputSegments.ext,
ext: outputSegments.ext
};
}
}
module.exports = File;