@visulima/fs
Version:
Human friendly file system utilities for Node.js
49 lines (45 loc) • 1.73 kB
JavaScript
;
const promises = require('node:fs/promises');
const node_zlib = require('node:zlib');
const utils = require('@visulima/path/utils');
const F_OK = require('./F_OK-CWSqQIdF.cjs');
const PermissionError = require('./PermissionError-QFMKgk2l.cjs');
const isAccessible = require('./isAccessible-ZNVGsSb7.cjs');
const assertValidFileOrDirectoryPath = require('./assertValidFileOrDirectoryPath-BMbgA-eI.cjs');
var __defProp = Object.defineProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
const decompressionMethods = {
brotli: node_zlib.brotliDecompress,
gzip: node_zlib.unzip,
none: /* @__PURE__ */ __name((buffer, callback) => {
callback(null, buffer);
}, "none")
};
const readFile = /* @__PURE__ */ __name(async (path, options) => {
assertValidFileOrDirectoryPath(path);
path = utils.toPath(path);
if (!await isAccessible(path)) {
throw new PermissionError(`unable to read the non-accessible file: ${path}`);
}
if (!await isAccessible(path, F_OK.R_OK)) {
throw new Error(`Unable to read the non-readable file: ${path}`);
}
const { buffer, compression, encoding, flag } = options ?? {};
return await promises.readFile(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");
module.exports = readFile;