1// Deprecated: use path.ts instead
2// File System APIs. Some custom APIs, but mostly a re-export a mix of built-in
3// Node.js sync+promise fs methods. For convenince.
4export {
5 createReadStream,
6 createWriteStream,
7 existsSync,
8 type FileHandle,
9 open,
10 readdir,
11 readdirSync,
12 readFile,
13 readFileSync,
14 rm,
15 rmSync,
16 stat,
17 statSync,
18 writeFile,
19 writeFileSync,
20};
21
22export function mkdir(dir: string) {
23 return nodeMkdir(dir, { recursive: true });
24}
25
26export function mkdirSync(dir: string) {
27 return nodeMkdirSync(dir, { recursive: true });
28}
29
30export type WriteFileAsyncOptions = Parameters<typeof writeFile>[2];
31
32export async function writeMkdir(
33 file: string,
34 contents: Uint8Array | string,
35 options?: WriteFileAsyncOptions,
36) {
37 await mkdir(path.dirname(file));
38 return writeFile(file, contents, options);
39}
40
41export function writeMkdirSync(file: string, contents: Uint8Array | string) {
42 mkdirSync(path.dirname(file));
43 return writeFileSync(file, contents);
44}
45
46export function readDirRecOptionalSync(dir: string) {
47 try {
48 return readdirSync(dir, { recursive: true, encoding: "utf8" });
49 } catch (err: any) {
50 if (err.code === "ENOENT") return [];
51 throw err;
52 }
53}
54
55export async function readJson<T>(file: string) {
56 return JSON.parse(await readFile(file, "utf-8")) as T;
57}
58
59export function readJsonSync<T>(file: string) {
60 return JSON.parse(readFileSync(file, "utf-8")) as T;
61}
62
63export async function removeEmptyDirectories(dir: string, removeRoot = false) {
64 try {
65 const entries = await readdir(dir, { withFileTypes: true });
66 let len = entries.length;
67 for (const entry of entries) {
68 if (entry.isDirectory()) {
69 const subDirPath = path.join(dir, entry.name);
70 if (await removeEmptyDirectories(subDirPath, true)) len -= 1;
71 }
72 }
73 if (len === 0) {
74 if (removeRoot) {
75 await rmdir(dir);
76 }
77 return true;
78 }
79 } catch (error: any) {
80 if (error.code === "ENOENT") {
81 // Directory doesn't exist, ignore
82 return;
83 }
84 throw error;
85 }
86 return false;
87}
88
89import {
90 createReadStream,
91 createWriteStream,
92 existsSync,
93 mkdirSync as nodeMkdirSync,
94 readdirSync,
95 readFileSync,
96 rmSync,
97 statSync,
98 writeFileSync,
99} from "node:fs";
100import {
101 type FileHandle,
102 mkdir as nodeMkdir,
103 open,
104 readdir,
105 readFile,
106 rm,
107 rmdir,
108 stat,
109 writeFile,
110} from "node:fs/promises";
111import * as path from "node:path";
112export { Stats } from "node:fs";