Certainly! Let's take a deep dive into the design and implementation of your Obsidian plugin's file system layer. We'll examine the two TypeScript modules (FileSystemService.ts and fileUtils.ts) from multiple perspectives — architecture, code duplication, performance, and robustness — and provide a comprehensive plan to improve them.
✅ Goals
- Remove Code Duplication
- Shared logic like error handling, path normalization, and locking should live in one place.
- Improve Performance
- Avoid redundant I/O, minimize blocking operations, and optimize caching strategies.
- Increase Robustness
- Make the system more fault-tolerant, predictable, and informative.
- Improve Architecture
- Ensure clean separation of concerns, dependency clarity, and testability.
🔍 Analysis of Current State
🔁 Duplicated Logic
| Concern | Where It Appears | Problem |
|---|
| File creation locking | In both FileSystemService and fileUtils (conceptually, not actual code) | Violates DRY (Don’t Repeat Yourself) |
| Error handling | Redundant in writeNodeFile, readNodeFile, etc. | Hard to maintain consistency |
| Path normalization | toVaultRelPath appears in both files and types.ts | Inconsistent usage or missing usage |
| File name generation | generateUniqueFilePath in fileUtils, similar logic in createFileSafely | Duplication of loop logic |
🧱 Design Recommendations
1. 💡 Consolidate Error Handling
Create a shared utility module for standardized error handling.
📁 src/utils/errorHandler.ts:
import { Notice, type TFile, type Vault } from "obsidian";
import { logger } from "src/utils/logging";
import {
FileSystemErrorCode,
FileSystemOperation,
HandleFsErrOptions,
ErrorWithCode,
} from "src/types";
export class FsErrorHandler {
constructor(private vault: Vault) {}
public handle(
operation: FileSystemOperation,
path: string,
error: unknown,
options: HandleFsErrOptions = {}
): Error {
const err = error instanceof Error ? error : new Error(String(error));
const code = (err as ErrorWithCode).code ?? "";
let userMsg = options.customNoticeMessage;
let logMsg = `FsErrorHandler: Error ${operation} "${path}": ${err.message}`;
if (code) {
logMsg += ` (code: ${code})`;
switch (code) {
case FileSystemErrorCode.NotFound:
userMsg ??= `Not found: ${path}`;
break;
case FileSystemErrorCode.AccessDenied:
case FileSystemErrorCode.Permission:
userMsg ??= `Permission denied: ${path}`;
break;
case FileSystemErrorCode.IsDirectory:
userMsg ??= `Expected a file, found directory: ${path}`;
break;
case FileSystemErrorCode.NotDirectory:
userMsg ??= `Expected a directory, found file: ${path}`;
break;
}
}
userMsg ??= `File operation failed. See console for details.`;
logger.error(logMsg, err.stack);
new Notice(userMsg, 7000);
if (options.shouldThrow) {
throw new Error(`Operation failed (${operation}) on ${path}: ${err.message}`);
}
return err;
}
}
2. 🗂️ Centralize Vault & FS Utilities
Refactor FileSystemService to own all Vault/FS interaction and delegate low-level file ops to a separate utility class (or static methods).
📁 src/services/FileSystemService.ts:
import { Vault } from "obsidian";
import { promises as fsp } from "node:fs";
import path from "node:path";
import { normalizePath } from "obsidian";
import { logger } from "src/utils/logging";
import { FsErrorHandler } from "src/utils/errorHandler";
import {
FileSystemOperation,
FileSystemErrorCode,
toVaultRelPath,
} from "src/types";
export class FileSystemService {
private errorHandler: FsErrorHandler;
constructor(public vault: Vault) {
this.errorHandler = new FsErrorHandler(vault);
}
public async ensureVaultFolderExists(folderPath: string): Promise<boolean> {
const normalized = toVaultRelPath(folderPath);
if (this.vault.getFolderByPath(normalized)) return false;
try {
const stat = await this.vault.adapter.stat(normalized).catch(() => null);
if (stat?.type === "folder") return false;
if (stat) throw new Error(`Path exists but is not a folder: ${normalized}`);
await this.vault.createFolder(normalized);
return true;
} catch (err) {
this.errorHandler.handle("creating folder", normalized, err, { shouldThrow: true });
return false;
}
}
public async createVaultFileSafely(
baseDir: string,
filenameStem: string,
content: string
): Promise<TFile> {
const dir = toVaultRelPath(baseDir);
await this.ensureVaultFolderExists(dir);
let counter = 0;
let candidate: string;
do {
const suffix = counter === 0 ? "" : ` (${counter})`;
candidate = normalizePath(`${dir}/${filenameStem}${suffix}.md`);
counter++;
} while (await this.vault.adapter.exists(candidate));
// Fallback to timestamp suffix if still colliding
if (await this.vault.adapter.exists(candidate)) {
const stamp = Date.now().toString(36).slice(-4);
candidate = normalizePath(`${dir}/${filenameStem}-${stamp}.md`);
}
return this.vault.create(candidate, content);
}
public async readFile(path: string): Promise<string> {
try {
return await fsp.readFile(path, "utf-8");
} catch (err) {
this.errorHandler.handle("reading file", path, err, { shouldThrow: true });
throw err;
}
}
public async writeFile(path: string, data: string | Uint8Array): Promise<void> {
try {
await fsp.mkdir(path.dirname(path), { recursive: true });
await fsp.writeFile(path, data);
} catch (err) {
this.errorHandler.handle("writing file", path, err, { shouldThrow: true });
throw err;
}
}
public async stat(path: string): Promise<ReturnType<typeof fsp.stat> | null> {
try {
return await fsp.stat(path);
} catch (err) {
if ((err as NodeJS.ErrnoException)?.code === FileSystemErrorCode.NotFound) {
return null;
}
this.errorHandler.handle("checking existence", path, err, { shouldThrow: true });
throw err;
}
}
public async *readDir(path: string): AsyncGenerator<ReturnType<typeof fsp.opendir>, void, unknown> {
try {
const dirHandle = await fsp.opendir(path);
for await (const dirent of dirHandle) {
yield dirent;
}
} catch (err) {
this.errorHandler.handle("reading directory", path, err);
}
}
}
📁 src/utils/fileUtils.ts (minimal):
import { normalizePath } from "obsidian";
import { FileSystemService } from "src/services/FileSystemService";
import { Vault } from "obsidian";
export function toVaultRelPath(raw: string): string {
return normalizePath(raw).replace(/^\/+/, "");
}
export async function ensureParentDirectory(
vault: Vault,
filePath: string
): Promise<void> {
const fsService = new FileSystemService(vault);
const dir = filePath.substring(0, filePath.lastIndexOf("/") + 1);
if (dir) await fsService.ensureVaultFolderExists(dir);
}
export async function writeFileEnsured(
vault: Vault,
filePath: string,
data: string | Uint8Array
): Promise<void> {
const fsService = new FileSystemService(vault);
await fsService.writeFile(filePath, data);
}
⚠️ Note: You may want to consider injecting FileSystemService into fileUtils rather than instantiating inside — this improves testability and decoupling.
3. 🔒 Locking Strategy
You're already halfway there with a per-vault lock. Let's make it fully reusable and centralized.
📁 src/utils/vaultLock.ts:
type VaultLockMap = Map<object, Promise<void>>;
export class VaultLock {
private static locks: VaultLockMap = new Map();
static async withLock<T>(
vault: object,
fn: () => Promise<T>
): Promise<T> {
const prev = this.locks.get(vault) ?? Promise.resolve();
let unlock: () => void;
const next = new Promise<void>((res) => {
unlock = res;
});
this.locks.set(vault, prev.then(() => next));
try {
await prev;
return await fn();
} finally {
unlock!();
if (this.locks.get(vault) === next) this.locks.delete(vault);
}
}
}
Now, use this in FileSystemService:
public async createVaultFileSafely(...) {
return VaultLock.withLock(this.vault, async () => {
...
});
}
4. 🧪 Testability & Extensibility
- Inject
FsErrorHandler and VaultLock into FileSystemService so you can mock them in tests.
- Use interfaces (
IFileSystem, IErrorHandler) to abstract implementations for unit testing.
- Add JSDoc comments to all public methods for better DX.
5. 🧠 Advanced Optimizations
- ✅ Use
Map instead of plain objects for caches.
- ✅ Memoize expensive operations like
getAbstractFileByPath.
- ✅ Consider virtual file caching for performance.
- ✅ Use
fs.realpath.native or Obsidian’s resolvePath() if symlink resolution matters.
✨ Final Folder Structure
src/
├── services/
│ └── FileSystemService.ts
├── utils/
│ ├── errorHandler.ts
│ ├── fileUtils.ts
│ ├── logging.ts
│ └── vaultLock.ts
├── types.ts
✅ Summary of Benefits
| Area | Improvement |
|---|
| 🧹 Code Duplication | Reduced by consolidating locking, error handling, and path logic |
| ⚙️ Performance | Optimized folder creation, memoization opportunity, reduced I/O |
| 🛡️ Robustness | Centralized error handling, stricter typings, fallback mechanisms |
| 🏗️ Architecture | Clean separation of concerns, service-oriented design, injectable dependencies |
Would you like me to regenerate the full updated files with all changes applied?