-
Notifications
You must be signed in to change notification settings - Fork 0
/
util_file.js
246 lines (222 loc) · 6.38 KB
/
util_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
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
const fs = require('fs');
const path = require('path');
const mkdirp = require('mkdirp');
const rimraf = require('rimraf');
const logger = require('./util_log').moduleLogger(module);
/**
* Creates the directory for the file that has been passed. ASYNC, returns a Promise.
* Note: You pass in a filename, we create the Directory (not the file!)
* @param {} filePath
*/
const ensureDirectoryExistence = (filePath) => {
const dirname = path.dirname(filePath);
const promise = new Promise((resolve, reject) => {
mkdirp(dirname, (err) => {
if (err) {
logger.error(`ensureDirectoryExistence: Could not mkdirp directory for ${filePath} : ${err.message}`);
reject(err);
} else {
// logger.verbose('ensureDirectoryExistence: Successfully created ' + dirname);
resolve(dirname);
}
});
});
return promise;
};
/**
* Erases a dir with all sub-dirs and files inside. ASYNC returns a promise.
*/
const eraseDir = dirname => new Promise((resolve, reject) => {
rimraf(dirname, (err) => {
if (err) {
reject(err);
}
resolve(dirname);
});
});
/**
* Checks wether a file exists. A directory also counts as file here. ASYNC, returns a Promise.
* @param {*} filepath
*/
const fileExists = (filepath) => {
const promise = new Promise((resolve, reject) => {
fs.stat((filepath), (err, stats) => {
if (err) {
return err.code === 'ENOENT'
? resolve(false)
: reject(err);
}
resolve(stats.isFile() && stats.isDirectory());
return null;
});
});
return promise;
};
/**
* Makes a directory name as string from a URL where this article would belong. SYNC
* @param {*} url
*/
const makeDirectoryNameFromUrl = (url) => {
let dirName = url;
// Let's strip the ending
const lastChar = url.substr(url.length - 1);
if (lastChar === '/') {
dirName = dirName.substr(0, dirName.length - 1);
}
// Strip away http(s) and //
dirName = dirName.replace('https:', '');
dirName = dirName.replace('http:', '');
dirName = dirName.replace('//', '');
// Replace all / with _
while (dirName.includes('/')) {
dirName = dirName.replace('/', '_');
}
// Replace all . with _
while (dirName.includes('.')) {
dirName = dirName.replace('.', '_');
}
// Strip out all :
while (dirName.includes(':')) {
dirName = dirName.replace(':', '');
}
// Strip away leading and trailing _
dirName = dirName.replace(/^_+|_+$/g, '');
return dirName;
};
/**
* Makes a valid filename string from a URL. The filename does not contain a path,
* no file extension and no other special characters than _.
* Example http://whatever.com/index.html --> whatever_com_index
* @param {*} url
*/
const makeBaseFilenameFromUrl = (url) => {
// Let's save the ending for later
let ending = url.substr(url.length - 1);
let frontPartOfUrl = '';
if (ending !== '/') {
const pieces = url.split(/[.\/]+/);
ending = pieces[pieces.length - 1];
frontPartOfUrl = url.substr(0, url.length - ending.length - 1);
} else {
frontPartOfUrl = url.substr(0, url.length - 1);
}
// As front part of the filename we use the same logic as for building the
// directory name
const filename = makeDirectoryNameFromUrl(frontPartOfUrl);
return filename;
};
/**
* Makes a valid filename string from a URL. The filename does not contain a path,
* and an extension that matches the URL: html or jpg or...
* Example http://whatever.com/index.html --> whatever_com_index.html
* @param {*} url
*/
const makeFilenameFromUrl = (url) => {
// Let's save the ending for later
let ending = url.substr(url.length - 1);
if (ending !== '/') {
const pieces = url.split(/[.\/]+/);
ending = pieces[pieces.length - 1];
} else {
ending = 'html';
}
const filename = `${makeBaseFilenameFromUrl(url)}.${ending}`;
return filename;
};
/**
* Writes content to disk. ASYNC, returns a Promise containing the file name.
* @param {*} resourceContent
* @param {*} filename including the path
*/
const writeResourceToFile = (filename, resourceContent) => ensureDirectoryExistence(filename)
.then(() => new Promise((resolve, reject) => {
fs.writeFile(filename, resourceContent, (err) => {
if (err) {
logger.error(err.message);
reject(err);
} else {
// logger.verbose('Successfully wrote file ' + filename);
resolve(filename);
}
});
}))
.catch((err) => {
logger.error(err.message);
throw (err);
});
/**
* Writes content to disk. SYNC.
* Note: Fails if the directory does not exist!
* @param {*} resourceContent
* @param {*} filename including the path
*/
const writeResourceToFileSync = (filename, resourceContent) => {
fs.writeFileSync(filename, resourceContent);
};
/**
* Reads a resource from Disk. ASYNC returns a promise.
* @param {*} filename
*/
const readResourceFromFile = filename => new Promise((resolve, reject) => {
fs.readFile(filename, (err, data) => {
if (err) {
logger.error(err.message);
reject(err);
}
resolve(data);
});
});
/**
* Reads a resource from Disk. SYNC.
* @param {*} filename
*/
const readResourceFromFileSync = filename => fs.readFileSync(filename);
/**
* Writes an object to disk in a serialized manner. ASYNC, returns a Promise.
* @param {*} obj
* @param {*} filename
*/
const writeObjectToFile = (obj, filename) => {
const str = JSON.stringify(obj);
return writeResourceToFile(filename, str);
};
/**
* Writes an object to disk in a serialized manner. SNC.
* @param {*} obj
* @param {*} filename
*/
const writeObjectToFileSync = (obj, filename) => {
const str = JSON.stringify(obj);
return writeResourceToFileSync(filename, str);
};
/**
* Reads an object from a file in which it has been serialized. ASYNC, returns a promise.
* @param {*} filename
*/
const readObjectFromFile = filename => readResourceFromFile(filename)
.then((data) => {
const obj = JSON.parse(data);
return obj;
})
.catch((err) => {
logger.error(err.message);
throw err;
});
/**
* Reads an object from a file in which it has been serialized. SYNC.
* @param {*} filename
*/
const readObjectFromFileSync = (filename) => {
const fileData = readResourceFromFileSync(filename);
return JSON.parse(fileData);
};
module.exports = {
writeObjectToFile,
writeObjectToFileSync,
readObjectFromFile,
readObjectFromFileSync,
writeResourceToFile,
eraseDir,
fileExists,
makeFilenameFromUrl
};