1 | 'use strict';
|
2 |
|
3 | let fs = require('fs');
|
4 | let path = require('path');
|
5 | let yaml = require('js-yaml');
|
6 |
|
7 | exports.readJSON = function(loc){
|
8 | try {
|
9 | return JSON.parse(fs.readFileSync(loc, 'utf8'));
|
10 | } catch (err) {
|
11 | err.message = `${loc}: ${err.message}`;
|
12 | throw err;
|
13 | }
|
14 | };
|
15 |
|
16 | exports.readYAML = function(loc) {
|
17 | try {
|
18 | return yaml.safeLoad(fs.readFileSync(loc, 'utf-8')) || {};
|
19 | } catch (err) {
|
20 | err.message = `${loc}: ${err.message}`;
|
21 | throw err;
|
22 | }
|
23 | };
|
24 |
|
25 | exports.readJS = function(loc){
|
26 | try {
|
27 | delete require.cache[loc];
|
28 | return require(loc);
|
29 | } catch (err) {
|
30 | err.message = `${loc}: ${err.message}`;
|
31 | throw err;
|
32 | }
|
33 | };
|
34 |
|
35 | exports.fileExists = function(filePath) {
|
36 | try {
|
37 | return fs.statSync(filePath).isFile();
|
38 | } catch (err) {
|
39 | return false;
|
40 | }
|
41 | };
|
42 |
|
43 | exports.dirExists = function(dirPath) {
|
44 | try {
|
45 | return fs.statSync(dirPath).isDirectory();
|
46 | } catch (err) {
|
47 | return false;
|
48 | }
|
49 | };
|
50 |
|
51 |
|
52 |
|
53 |
|
54 |
|
55 |
|
56 |
|
57 |
|
58 | exports.readFile = function(loc){
|
59 | let content = null;
|
60 | switch (path.extname(loc)) {
|
61 | case '.js':
|
62 | content = exports.readJS(loc);
|
63 | break;
|
64 | case '.json':
|
65 | content = exports.readJSON(loc);
|
66 | break;
|
67 | case '.yml':
|
68 | case '.yaml':
|
69 | content = exports.readYAML(loc);
|
70 | break;
|
71 | default:
|
72 | break;
|
73 | }
|
74 | return content;
|
75 | };
|
76 |
|
77 |
|
78 |
|
79 |
|
80 |
|
81 |
|
82 |
|
83 |
|
84 |
|
85 | exports.readFileAny = function(files){
|
86 | for(const file of files){
|
87 | if(fs.existsSync(file)){
|
88 | return exports.readFile(file);
|
89 | }
|
90 | }
|
91 | return null;
|
92 | };
|
93 |
|
94 |
|
95 |
|
96 |
|
97 |
|
98 |
|
99 |
|
100 |
|
101 |
|
102 |
|
103 | exports.deleteFolderRecursive = function(filePath, remainRootDir) {
|
104 | if (fs.existsSync(filePath)) {
|
105 | fs.readdirSync(filePath).forEach((file) => {
|
106 | const currentPath = filePath + '/' + file;
|
107 | if (fs.lstatSync(currentPath).isDirectory()) {
|
108 | exports.deleteFolderRecursive(currentPath);
|
109 | } else {
|
110 | fs.unlinkSync(currentPath);
|
111 | }
|
112 | });
|
113 |
|
114 | if(!remainRootDir) {
|
115 | fs.rmdirSync(filePath);
|
116 | }
|
117 | }
|
118 | };
|
119 |
|
120 | exports.getFileSize = function(filename) {
|
121 | try {
|
122 | const stats = fs.statSync(filename);
|
123 |
|
124 | return stats['size'] > 1024
|
125 | ? (stats['size'] / 1024).toFixed(2) + ' KB'
|
126 | : stats['size'] + ' Bytes';
|
127 | } catch (err) {
|
128 | return null;
|
129 | }
|
130 | };
|