-
Notifications
You must be signed in to change notification settings - Fork 4
/
files.ts
65 lines (54 loc) · 1.66 KB
/
files.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
import fs, { mkdir, readFile, rm, writeFile } from "fs"
import { join } from "path"
import { promisify } from "util"
const statP = promisify(fs.stat)
const readFileP = promisify(readFile)
export type FilePath = string
export const readFileContents = async (pathToFile: FilePath): Promise<string> =>
readFileP(pathToFile, { encoding: "utf8" }).then((contents) =>
contents.toString(),
)
export const fileExists = async (pathToFile: FilePath): Promise<boolean> =>
statP(pathToFile)
.then((s) => s.isFile())
.catch(() => false)
export const dirExists = async (pathToDir: FilePath): Promise<boolean> =>
statP(pathToDir)
.then((s) => s.isDirectory())
.catch(() => false)
export const createDir = async (pathToDir: FilePath): Promise<boolean> =>
new Promise((resolve, reject) => {
mkdir(pathToDir, { recursive: true }, (err) => {
if (err) reject(err)
else resolve(true)
})
})
export const removeDir = async (pathToDir: FilePath): Promise<boolean> =>
new Promise((resolve, reject) => {
rm(pathToDir, { recursive: true }, (err) => {
if (err) reject(err)
else resolve(true)
})
})
export const createFile = async (
pathToFile: FilePath,
content: string,
): Promise<boolean> =>
new Promise((resolve, reject) => {
writeFile(pathToFile, content, (err) => {
if (err) reject(err)
else resolve(true)
})
})
export const expandFilePath = (
baseDir: FilePath,
filePath: FilePath,
): FilePath => {
if (filePath.startsWith("/") || filePath.startsWith("~")) {
return filePath
}
if (filePath.startsWith("./")) {
return join(baseDir, filePath.slice(2))
}
return join(baseDir, filePath)
}