sitegen/framework/lib/fs.ts

83 lines
1.7 KiB
TypeScript
Raw Normal View History

2025-06-07 02:25:06 -07:00
// File System APIs. Some custom APIs, but mostly a re-export a mix of built-in
// Node.js sync+promise fs methods. For convenince.
export {
2025-06-27 19:40:19 -07:00
createReadStream,
createWriteStream,
2025-06-07 02:25:06 -07:00
existsSync,
2025-06-27 19:40:19 -07:00
open,
2025-06-07 02:25:06 -07:00
readdir,
readdirSync,
readFile,
readFileSync,
rm,
rmSync,
stat,
statSync,
writeFile,
writeFileSync,
};
export function mkdir(dir: string) {
return nodeMkdir(dir, { recursive: true });
}
export function mkdirSync(dir: string) {
return nodeMkdirSync(dir, { recursive: true });
}
2025-06-13 00:13:22 -07:00
export type WriteFileAsyncOptions = Parameters<typeof writeFile>[2];
export async function writeMkdir(
file: string,
contents: Buffer | string,
options?: WriteFileAsyncOptions,
) {
await mkdir(path.dirname(file));
2025-06-13 00:13:22 -07:00
return writeFile(file, contents, options);
}
2025-06-07 02:25:06 -07:00
export function writeMkdirSync(file: string, contents: Buffer | string) {
mkdirSync(path.dirname(file));
return writeFileSync(file, contents);
}
export function readDirRecOptionalSync(dir: string) {
try {
2025-06-09 00:12:41 -07:00
return readdirSync(dir, { recursive: true, encoding: "utf8" });
2025-06-07 02:25:06 -07:00
} catch (err: any) {
if (err.code === "ENOENT") return [];
throw err;
}
}
2025-06-10 01:13:59 -07:00
export async function readJson<T>(file: string) {
return JSON.parse(await readFile(file, "utf-8")) as T;
}
export function readJsonSync<T>(file: string) {
return JSON.parse(readFileSync(file, "utf-8")) as T;
}
2025-06-07 02:25:06 -07:00
import * as path from "node:path";
import {
2025-06-27 19:40:19 -07:00
createReadStream,
createWriteStream,
2025-06-07 02:25:06 -07:00
existsSync,
mkdirSync as nodeMkdirSync,
readdirSync,
readFileSync,
rmSync,
statSync,
writeFileSync,
} from "node:fs";
import {
mkdir as nodeMkdir,
2025-06-27 19:40:19 -07:00
open,
2025-06-07 02:25:06 -07:00
readdir,
readFile,
rm,
stat,
writeFile,
} from "node:fs/promises";
2025-06-27 19:40:19 -07:00
export { Stats } from "node:fs";