2019-12-03 23:28:59 +08:00
|
|
|
import * as fs from 'fs'
|
|
|
|
|
|
|
|
export function directoryExistsSync(path: string, required?: boolean): boolean {
|
|
|
|
if (!path) {
|
|
|
|
throw new Error("Arg 'path' must not be empty")
|
|
|
|
}
|
|
|
|
|
|
|
|
let stats: fs.Stats
|
|
|
|
try {
|
|
|
|
stats = fs.statSync(path)
|
|
|
|
} catch (error) {
|
2021-10-19 22:52:57 +08:00
|
|
|
if ((error as any)?.code === 'ENOENT') {
|
2019-12-03 23:28:59 +08:00
|
|
|
if (!required) {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
throw new Error(`Directory '${path}' does not exist`)
|
|
|
|
}
|
|
|
|
|
|
|
|
throw new Error(
|
2021-10-19 22:52:57 +08:00
|
|
|
`Encountered an error when checking whether path '${path}' exists: ${(error as any)
|
|
|
|
?.message ?? error}`
|
2019-12-03 23:28:59 +08:00
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
if (stats.isDirectory()) {
|
|
|
|
return true
|
|
|
|
} else if (!required) {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
throw new Error(`Directory '${path}' does not exist`)
|
|
|
|
}
|
|
|
|
|
|
|
|
export function existsSync(path: string): boolean {
|
|
|
|
if (!path) {
|
|
|
|
throw new Error("Arg 'path' must not be empty")
|
|
|
|
}
|
|
|
|
|
|
|
|
try {
|
|
|
|
fs.statSync(path)
|
|
|
|
} catch (error) {
|
2021-10-19 22:52:57 +08:00
|
|
|
if ((error as any)?.code === 'ENOENT') {
|
2019-12-03 23:28:59 +08:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
throw new Error(
|
2021-10-19 22:52:57 +08:00
|
|
|
`Encountered an error when checking whether path '${path}' exists: ${(error as any)
|
|
|
|
?.message ?? error}`
|
2019-12-03 23:28:59 +08:00
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
export function fileExistsSync(path: string): boolean {
|
|
|
|
if (!path) {
|
|
|
|
throw new Error("Arg 'path' must not be empty")
|
|
|
|
}
|
|
|
|
|
|
|
|
let stats: fs.Stats
|
|
|
|
try {
|
|
|
|
stats = fs.statSync(path)
|
|
|
|
} catch (error) {
|
2021-10-19 22:52:57 +08:00
|
|
|
if ((error as any)?.code === 'ENOENT') {
|
2019-12-03 23:28:59 +08:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
throw new Error(
|
2021-10-19 22:52:57 +08:00
|
|
|
`Encountered an error when checking whether path '${path}' exists: ${(error as any)
|
|
|
|
?.message ?? error}`
|
2019-12-03 23:28:59 +08:00
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!stats.isDirectory()) {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
return false
|
|
|
|
}
|