@stryke/fs
Version:
A package containing various file system utilities that expand the functionality of NodeJs's built-in `fs` module.
57 lines (55 loc) • 2.52 kB
JavaScript
import { createDirectory, createDirectorySync } from "./helpers.mjs";
import { findFilePath } from "@stryke/path";
import { Buffer } from "node:buffer";
import { existsSync, readFileSync, writeFileSync } from "node:fs";
import { readFile, writeFile } from "node:fs/promises";
//#region src/buffer.ts
/**
* Reads a file from the given path and returns its content as an ArrayBuffer. The file is expected to be located relative to the current directory of this module.
*
* @param filePath - The path to the file to read.
* @returns The content of the file as an ArrayBuffer.
*/
async function readFileBuffer(filePath) {
if (!filePath) throw new Error("No file path provided to read data");
if (!existsSync(filePath)) throw new Error(`File does not exist at path: ${filePath}`);
const b = await readFile(filePath);
return b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength);
}
/**
* Reads a file from the given path and returns its content as an ArrayBuffer. The file is expected to be located relative to the current directory of this module.
*
* @param filePath - The path to the file to read.
* @returns The content of the file as an ArrayBuffer.
*/
function readFileBufferSync(filePath) {
if (!filePath) throw new Error("No file path provided to read data");
if (!existsSync(filePath)) throw new Error(`File does not exist at path: ${filePath}`);
const b = readFileSync(filePath);
return b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength);
}
/**
* Writes an ArrayBuffer to a file at the specified path.
*
* @param filePath - The path to the file where the data should be written.
* @param data - The ArrayBuffer containing the data to write.
*/
async function writeFileBuffer(filePath, data) {
if (!filePath) throw new Error("No file path provided to write data");
if (!existsSync(findFilePath(filePath))) await createDirectory(findFilePath(filePath));
await writeFile(filePath, Buffer.from(data));
}
/**
* Writes an ArrayBuffer to a file at the specified path.
*
* @param filePath - The path to the file where the data should be written.
* @param data - The ArrayBuffer containing the data to write.
*/
function writeFileBufferSync(filePath, data) {
if (!filePath) throw new Error("No file path provided to write data");
if (!existsSync(findFilePath(filePath))) createDirectorySync(findFilePath(filePath));
writeFileSync(filePath, Buffer.from(data));
}
//#endregion
export { readFileBuffer, readFileBufferSync, writeFileBuffer, writeFileBufferSync };
//# sourceMappingURL=buffer.mjs.map