Skip to content

Instantly share code, notes, and snippets.

@nikoheikkila
Last active February 28, 2023 06:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nikoheikkila/8a9c13483ebf5f081f41704a85b551ec to your computer and use it in GitHub Desktop.
Save nikoheikkila/8a9c13483ebf5f081f41704a85b551ec to your computer and use it in GitHub Desktop.
In-Memory Filesystem Repository for Node.js & TypeScript
import * as fs from "node:fs/promises";
type Disk = Map<string, string>;
interface FileSystemAdapter {
readFile(path: string): Promise<string>;
writeFile(path: string, content: string): Promise<void>;
deleteFile(path: string): Promise<void>;
}
class InMemoryFileSystem implements FileSystemAdapter {
private readonly disk: Disk;
constructor(disk?: Disk) {
this.disk = disk ?? new Map();
}
public async readFile(path: string): Promise<string> {
const contents = this.disk.get(path);
if (!contents) {
throw new Error(`File ${path} not found or not readable`);
}
return contents;
}
public async writeFile(path: string, content: string): Promise<void> {
this.disk.set(path, content);
}
public async deleteFile(path: string): Promise<void> {
this.disk.delete(path);
}
}
class RealFileSystem implements FileSystemAdapter {
private readonly encoding: 'utf8' = 'utf8';
public async readFile(path: string): Promise<string> {
return fs.readFile(path, { encoding: this.encoding });
}
public async writeFile(path: string, content: string): Promise<void> {
fs.writeFile(path, content, { encoding: this.encoding });
}
public async deleteFile(path: string): Promise<void> {
fs.unlink(path);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment