-
Notifications
You must be signed in to change notification settings - Fork 7
/
fileUtil.ts
95 lines (86 loc) · 2.64 KB
/
fileUtil.ts
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
import * as fs from 'fs';
import * as fse from 'fs-extra';
import * as path from 'path';
/**
* Class which holds helper tools when working with files.
*
* @export
* @class FileUtil
*/
export class FileUtil {
/**
* Normalize folder path
* @param {string} filePath path to be normalized
* @returns {*} normalized path
*/
public normalizePath(filePath: string): string {
return path.isAbsolute(filePath) ? (path.normalize(filePath)) :
`${process.cwd()}${process.platform !== 'win32' ? '/' : '\\'}${path.normalize(filePath)}`;
}
/**
* Check if a filePath represents the path for a directory or a file
* @param {string} filePath - relative or absolute file path
* @returns {boolean} check if path is dir
*/
public isDirectory(filePath: string): boolean {
const normalizedFilePath: string = this.normalizePath(filePath);
return Boolean(
normalizedFilePath.substring(
normalizedFilePath.lastIndexOf('/'),
normalizedFilePath.length,
).indexOf('.'),
);
}
/**
* Create directory if not exist
* @param {string} filePath path where the directory should be created.
* @returns {Promise} directory created
*/
public async createDirectory(filePath: string): Promise<boolean> {
const normalizedFilePath: string = this.normalizePath(filePath);
return new Promise<boolean>((resolve: Function, reject: Function): void => {
fs.stat(normalizedFilePath, (err: Error, stat: fs.Stats) => {
if (err) {
/* istanbul ignore next */
fse.ensureDir(normalizedFilePath, (ensureDirErr: Error) => {
if (ensureDirErr) {
reject(ensureDirErr);
} else {
resolve(true);
}
});
} else {
resolve(Boolean(stat.isDirectory()));
}
});
});
}
/**
* Join list of paths
* @param {Array<string>} paths array of paths that need to be merged
* @returns {string} merged path
*/
public joinPaths(...paths: string[]): string {
return path.join(...paths);
}
/**
* Writes content into file.
*
* @param {string} filePath - destination file
* @param {string} content - content to be written
* @returns {Promise} file written
*/
public async writeFile(filePath: string, content: string): Promise<boolean> {
return new Promise<boolean>((resolve: Function, reject: Function): void => {
fs.writeFile(filePath, content, {encoding: 'UTF-8'}, (err: Error) => {
if (err) {
/* istanbul ignore next */
reject(err);
} else {
resolve();
}
});
});
}
}
export default new FileUtil();