Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion packages/node/src/node-fs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@ import path from "node:path";
import { argv, chdir, cwd } from "node:process";
import { promisify } from "node:util";

import type { IBaseFileSystem, IFileSystem } from "@file-services/types";
import type { IBaseFileSystem, IFileSystem, WatchOptions } from "@file-services/types";
import { createFileSystem } from "@file-services/utils";
import { INodeWatchServiceOptions, NodeWatchService } from "./watch-service";
import { RecursiveFSWatcher } from "./recursive-fs-watcher";

const caseSensitive = !fs.existsSync(argv[0]!.toUpperCase());
const fsPromisesExists = promisify(fs.exists);
Expand All @@ -19,16 +20,28 @@ export function createNodeFs(options?: ICreateNodeFsOptions): IFileSystem {
}

export function createBaseNodeFs(options?: ICreateNodeFsOptions): IBaseFileSystem {
const originalWatch = fs.watch;
const watch = process.platform === "linux" ? wrapWithOwnRecursiveImpl(originalWatch) : originalWatch;
return {
...path,
chdir,
cwd,
watchService: new NodeWatchService(options && options.watchOptions),
caseSensitive,
...fs,
watch,
promises: {
...fs.promises,
exists: fsPromisesExists,
},
};
}

function wrapWithOwnRecursiveImpl(originalWatch: typeof fs.watch) {
return (targetPath: string, options?: WatchOptions) => {
if (options?.recursive) {
return new RecursiveFSWatcher(targetPath, options);
}
return originalWatch(targetPath, options);
};
}
97 changes: 97 additions & 0 deletions packages/node/src/recursive-fs-watcher.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import EventEmitter, { once } from "node:events";
import { lstatSync, readdirSync, watch, type FSWatcher, type Stats, type WatchOptions } from "node:fs";
import path from "node:path";

export interface WatcherEvents {
error: [error: Error];
change: [eventType: "change" | "rename", relativePath: string];
close: [];
}

export class RecursiveFSWatcher extends EventEmitter<WatcherEvents> {
#directoryPathToWatcher = new Map<string, FSWatcher>();

constructor(
private rootDirectoryPath: string,
private options?: WatchOptions,
) {
super();
if (!options?.recursive) {
throw new Error("RecursiveFSWatcher requires recursive option to be set");
}
this.options = { ...options, recursive: false };
this.#watchDirectoryDeep(rootDirectoryPath);
}

close() {
Promise.all(
Array.from(this.#directoryPathToWatcher, async ([directoryPath, watcher]) => {
this.#closeExistingWatcher(directoryPath, watcher);
await once(watcher, "close");
}),
)
.then(() => {
this.emit("close");
})
.catch((e) => {
this.emit("error", e as Error);
});
}

#watchDirectoryDeep(directoryPath: string): void {
this.#watchDirectory(directoryPath);
try {
for (const entry of readdirSync(directoryPath, { withFileTypes: true })) {
if (entry.isDirectory()) {
this.#watchDirectoryDeep(path.join(directoryPath, entry.name));
}
}
} catch (e) {
this.emit("error", e as Error);
}
}

#watchDirectory(directoryPath: string): void {
try {
this.#closeExistingWatcher(directoryPath);
const watcher = watch(directoryPath, this.options);
watcher.on("change", (eventType, relativePath) => {
if (typeof relativePath !== "string" || (eventType !== "change" && eventType !== "rename")) {
return;
}
const eventPath = path.join(directoryPath, relativePath);
this.emit("change", eventType, path.relative(this.rootDirectoryPath, eventPath));
if (eventType === "rename") {
this.#closeExistingWatcher(eventPath);
if (this.#lstatSyncSafe(eventPath)?.isDirectory()) {
this.#watchDirectoryDeep(eventPath);
}
}
});
watcher.on("error", (e) => {
this.emit("error", e);
});
this.#directoryPathToWatcher.set(directoryPath, watcher);
} catch (e) {
this.emit("error", e as Error);
}
}

#closeExistingWatcher(directoryPath: string, watcher?: FSWatcher) {
const existingWatcher = watcher ?? this.#directoryPathToWatcher.get(directoryPath);
if (existingWatcher) {
this.#directoryPathToWatcher.delete(directoryPath);
existingWatcher.removeAllListeners("change");
existingWatcher.close();
}
}

#lstatSyncSafe(targetPath: string): Stats | undefined {
try {
return lstatSync(targetPath, { throwIfNoEntry: false });
} catch (e) {
this.emit("error", e as Error);
return undefined;
}
}
}