@stryke/fs
Version:
A package containing various file system utilities that expand the functionality of NodeJs's built-in `fs` module.
84 lines (82 loc) • 2.66 kB
JavaScript
import { readFile, readFileSync } from "./read-file.mjs";
import { writeFile, writeFileSync } from "./write-file.mjs";
import { findFileExtension } from "@stryke/path";
import { isSetString } from "@stryke/type-checks";
import { StormJSON } from "@stryke/json/storm-json";
import { isError } from "@stryke/type-checks/is-error";
//#region src/json.ts
/**
* Reads a JSON file and returns the object the JSON content represents.
*
* @param path - A path to a file.
* @param options - JSON parse options
* @returns Object the JSON content of the file represents
*/
function readJsonFileSync(path, options) {
const content = readFileSync(path);
try {
return StormJSON.parse(isSetString(content) ? content.trim() : "{}", {
expectComments: findFileExtension(path) === "jsonc",
...options
});
} catch (error) {
if (isError(error)) {
error.message = error.message.replace("JSON", path);
throw error;
}
throw new Error(`Failed to parse JSON: ${path}`);
}
}
/**
* Reads a JSON file and returns the object the JSON content represents.
*
* @param path - A path to a file.
* @param options - JSON parse options
* @returns Object the JSON content of the file represents
*/
async function readJsonFile(path, options = {}) {
const content = await readFile(path);
try {
return StormJSON.parse(isSetString(content) ? content.trim() : "{}", {
expectComments: findFileExtension(path) === "jsonc",
...options
});
} catch (error) {
if (isError(error)) {
error.message = error.message.replace("JSON", path);
throw error;
}
throw new Error(`Failed to parse JSON: ${path}`);
}
}
/**
* Serializes the given data to JSON and writes it to a file.
*
* @param path - A path to a file.
* @param data - data which should be serialized to JSON and written to the file
* @param options - JSON serialize options
*/
function writeJsonFileSync(path, data, options = {}) {
const serializedJson = StormJSON.stringify(data, {
spaces: 2,
...options
});
return writeFileSync(path, options?.appendNewLine ? `${serializedJson}\n` : serializedJson);
}
/**
* Serializes the given data to JSON and writes it to a file asynchronously.
*
* @param path - A path to a file.
* @param data - data which should be serialized to JSON and written to the file
* @param options - JSON serialize options
*/
async function writeJsonFile(path, data, options = {}) {
const serializedJson = StormJSON.stringify(data, {
spaces: 2,
...options
});
return writeFile(path, options?.appendNewLine ? `${serializedJson}\n` : serializedJson);
}
//#endregion
export { readJsonFile, readJsonFileSync, writeJsonFile, writeJsonFileSync };
//# sourceMappingURL=json.mjs.map