forked from noxious/server
72 lines
1.7 KiB
TypeScript
72 lines
1.7 KiB
TypeScript
import fs from 'fs'
|
|
import path from 'path'
|
|
|
|
import config from '#application/config'
|
|
|
|
class Storage {
|
|
private readonly baseDir: string
|
|
private readonly rootDir: string
|
|
|
|
constructor() {
|
|
this.rootDir = process.cwd()
|
|
this.baseDir = config.ENV === 'development' ? 'src' : 'dist'
|
|
}
|
|
|
|
/**
|
|
* Gets path relative to project root
|
|
*/
|
|
public getRootPath(folder: string, ...additionalSegments: string[]): string {
|
|
return path.join(this.rootDir, folder, ...additionalSegments)
|
|
}
|
|
|
|
/**
|
|
* Gets path relative to app directory (src/dist)
|
|
*/
|
|
public getAppPath(folder: string, ...additionalSegments: string[]): string {
|
|
return path.join(this.rootDir, this.baseDir, folder, ...additionalSegments)
|
|
}
|
|
|
|
/**
|
|
* Gets path relative to public directory
|
|
*/
|
|
public getPublicPath(folder: string, ...additionalSegments: string[]): string {
|
|
return path.join(this.rootDir, 'public', folder, ...additionalSegments)
|
|
}
|
|
|
|
/**
|
|
* Checks if a path exists
|
|
* @throws Error if path is empty or invalid
|
|
*/
|
|
public doesPathExist(pathToCheck: string): boolean {
|
|
if (!pathToCheck) {
|
|
throw new Error('Path cannot be empty')
|
|
}
|
|
|
|
try {
|
|
fs.accessSync(pathToCheck, fs.constants.F_OK)
|
|
return true
|
|
} catch (e) {
|
|
return false
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Creates a directory and any necessary parent directories
|
|
* @throws Error if directory creation fails
|
|
*/
|
|
public createDir(dirPath: string): void {
|
|
if (!dirPath) {
|
|
throw new Error('Directory path cannot be empty')
|
|
}
|
|
|
|
try {
|
|
fs.mkdirSync(dirPath, { recursive: true })
|
|
} catch (error) {
|
|
const typedError = error as Error
|
|
throw new Error(`Failed to create directory: ${typedError.message}`)
|
|
}
|
|
}
|
|
}
|
|
|
|
export default new Storage()
|