UNPKG

@visulima/fs

Version:

Human friendly file system utilities for Node.js

66 lines (59 loc) 2.32 kB
import { createRequire as __cjs_createRequire } from "node:module"; const __cjs_require = __cjs_createRequire(import.meta.url); const __cjs_getProcess = typeof globalThis !== "undefined" && typeof globalThis.process !== "undefined" ? globalThis.process : process; const __cjs_getBuiltinModule = (module) => { // Check if we're in Node.js and version supports getBuiltinModule if (typeof __cjs_getProcess !== "undefined" && __cjs_getProcess.versions && __cjs_getProcess.versions.node) { const [major, minor] = __cjs_getProcess.versions.node.split(".").map(Number); // Node.js 20.16.0+ and 22.3.0+ if (major > 22 || (major === 22 && minor >= 3) || (major === 20 && minor >= 16)) { return __cjs_getProcess.getBuiltinModule(module); } } // Fallback to createRequire return __cjs_require(module); }; const { readFile: readFile$1 } = __cjs_getBuiltinModule("node:fs/promises"); const { unzip, brotliDecompress } = __cjs_getBuiltinModule("node:zlib"); import { toPath } from '@visulima/path/utils'; import { R_OK } from './F_OK-BalxCn9n.js'; import PermissionError from './PermissionError-CjoiJgip.js'; import isAccessible from './isAccessible-iOp0Bou6.js'; import assertValidFileOrDirectoryPath from './assertValidFileOrDirectoryPath-8HANmVjk.js'; const decompressionMethods = { brotli: brotliDecompress, gzip: unzip, none: (buffer, callback) => { callback(null, buffer); } }; const readFile = async (path, options) => { assertValidFileOrDirectoryPath(path); path = toPath(path); if (!await isAccessible(path)) { throw new PermissionError(`unable to read the non-accessible file: ${path}`); } if (!await isAccessible(path, R_OK)) { throw new Error(`Unable to read the non-readable file: ${path}`); } const { buffer, compression, encoding, flag } = options ?? {}; return await readFile$1(path, flag ? { encoding, flag } : { encoding }).then( async (content) => await new Promise((resolve, reject) => { decompressionMethods[compression ?? "none"](content, (error, result) => { if (error) { reject(error); } else { resolve(buffer ? result : result.toString()); } }); }) ).catch((error) => { throw error; }); }; export { readFile as default };