-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfile.ts
More file actions
56 lines (48 loc) · 1.71 KB
/
file.ts
File metadata and controls
56 lines (48 loc) · 1.71 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
import * as fs from 'node:fs/promises';
import * as os from 'node:os';
import path from 'node:path';
export async function createStartupShellScriptsIfNotExists(): Promise<void> {
// TODO: Support bash in the future
const open = await fs.open(`${os.homedir}/.zshrc`, 'a');
await open.close();
}
export class FileUtils {
static async fileExists(filePath: string, throwIfExistsButNotFile = true): Promise<boolean> {
try {
const result = await fs.lstat(path.resolve(filePath))
if (throwIfExistsButNotFile && !result.isFile()) {
throw new Error(`Dir found at ${filePath} instead of a file`)
}
return true;
} catch(e) {
return false;
}
}
static async dirExists(dirPath: string, throwIfExistsButNotFile = true): Promise<boolean> {
try {
const result = await fs.lstat(path.resolve(dirPath))
if (throwIfExistsButNotFile && !result.isDirectory()) {
throw new Error(`File found at ${dirPath} instead of a file`)
}
return true;
} catch(e) {
return false;
}
}
static async isDir(fileOrDir: string): Promise<boolean> {
const lstat = await fs.lstat(path.resolve(fileOrDir))
return lstat.isDirectory()
}
static async readFile(filePath: string): Promise<string | undefined> {
const resolvedPath = path.resolve(filePath);
return fs.readFile(resolvedPath, 'utf8')
}
static async writeFile(filePath: string, contents: string): Promise<void> {
const resolvedPath = path.resolve(filePath);
await fs.writeFile(resolvedPath, contents, 'utf8')
}
static async createFolder(dirPath: string): Promise<void> {
const resolvedPath = path.resolve(dirPath);
await fs.mkdir(resolvedPath, { recursive: true });
}
}