@nasriya/atomix
Version:
Composable helper functions for building reliable systems
81 lines (80 loc) • 3.1 kB
JavaScript
import fs from 'fs';
import path from 'path';
import { getAccessOptions } from './assets/helpers.js';
import stringsUtils from '../data-types/string/strings-utils.js';
import fsPromises from './assets/fs-promises.js';
class FileSystemUtils {
/**
* Provides async promises for file system operations.
*
* @returns The fsPromises instance.
* @since v1.0.0
*/
get promises() { return fsPromises; }
/**
* 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.basename(filePath)} is not a JSON file.`);
}
const strContent = fs.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 (!stringsUtils.guard.isString(filePath)) {
throw new Error(`The filePath should be string, instead got ${typeof filePath}`);
}
const configs = getAccessOptions(options);
try {
fs.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;
export default fileSystem;