UNPKG

@visulima/fs

Version:

Human friendly file system utilities for Node.js

47 lines (44 loc) 1.69 kB
import { readFile as readFile$1 } from 'node:fs/promises'; import { brotliDecompress, unzip } from 'node:zlib'; import { toPath } from '@visulima/path/utils'; import { R_OK } from './F_OK-JER1LjUr.mjs'; import PermissionError from './PermissionError-CqGMI9qC.mjs'; import isAccessible from './isAccessible-Bonsm1Ez.mjs'; import assertValidFileOrDirectoryPath from './assertValidFileOrDirectoryPath-BWWgA1wj.mjs'; var __defProp = Object.defineProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); const decompressionMethods = { brotli: brotliDecompress, gzip: unzip, none: /* @__PURE__ */ __name((buffer, callback) => { callback(null, buffer); }, "none") }; const readFile = /* @__PURE__ */ __name(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) => ( // eslint-disable-next-line compat/compat 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; }); }, "readFile"); export { readFile as default };