UNPKG

@nasriya/atomix

Version:

Composable helper functions for building reliable systems

86 lines (85 loc) 3.47 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const fs_1 = __importDefault(require("fs")); const path_1 = __importDefault(require("path")); const helpers_1 = require("./assets/helpers"); const strings_utils_1 = __importDefault(require("../data-types/string/strings-utils")); const fs_promises_1 = __importDefault(require("./assets/fs-promises")); class FileSystemUtils { /** * Provides async promises for file system operations. * * @returns The fsPromises instance. * @since v1.0.0 */ get promises() { return fs_promises_1.default; } /** * Loads a JSON file from the given path, returning its contents as a Record or Array. * * @param filePath - The path to the JSON file to load. * @returns The contents of the JSON file as a Record or Array. * @throws Error if the file does not exist, is not a valid JSON file, or if the user does not have enough permissions to access the file. * @since v1.0.0 * @example * const configFile = loadJSON('config.json'); * // configFile is the contents of the file as a Record or Array */ loadJSONSync(filePath) { try { this.canAccessSync(filePath, { throwError: true, permissions: 'Read' }); if (!filePath.toLowerCase().endsWith('.json')) { throw new Error(`${path_1.default.basename(filePath)} is not a JSON file.`); } const strContent = fs_1.default.readFileSync(filePath, { encoding: 'utf-8' }); try { const file = JSON.parse(strContent); return file; } catch (error) { throw new Error(`The default configuration file is damaged, corrupted, or not a valid JSON file.`); } } catch (error) { if (error instanceof Error) { error.message = `Unable to load JSON file: ${error.message}`; } throw error; } } /** * Checks if the given file path is accessible by the current user. * * @param filePath - The path to the file to check. * @param options - An object containing the property "throwError". * @param options.throwError - If true, throws an error if the file is not accessible. If false, returns false. * @returns True if the file is accessible, false otherwise. * @since v1.0.0 * @example * const canAccess = canAccessSync('path/to/file.txt'); * // canAccess is true if the file is accessible, false otherwise */ canAccessSync(filePath, options) { if (!strings_utils_1.default.guard.isString(filePath)) { throw new Error(`The filePath should be string, instead got ${typeof filePath}`); } const configs = (0, helpers_1.getAccessOptions)(options); try { fs_1.default.accessSync(filePath, configs.mode); return true; } catch (error) { if (configs.throwError) { if (error instanceof Error) { error.message = `You cannot access this path: ${error.message}`; } throw error; } return false; } } } const fileSystem = new FileSystemUtils; exports.default = fileSystem;