Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/amanvarshney01/create-better-t-stack/llms.txt

Use this file to discover all available pages before exploring further.

The VirtualFileSystem class provides an in-memory filesystem for generating and manipulating files without disk I/O.

Overview

The VirtualFileSystem is powered by memfs and supports standard file operations in memory. It’s used internally by createVirtual() and the template generator.

Class API

Constructor

const vfs = new VirtualFileSystem();
Creates a new in-memory filesystem. Source: ~/workspace/source/packages/template-generator/src/core/virtual-fs.ts:8

Methods

writeFile()

Write a file to the virtual filesystem.
writeFile(filePath: string, content: string, sourcePath?: string): void
filePath
string
required
Path where the file should be written (e.g., "src/index.ts")
content
string
required
File contents
sourcePath
string
Original template path (for tracking)
Example:
vfs.writeFile("package.json", JSON.stringify({ name: "my-app" }, null, 2));
vfs.writeFile("src/index.ts", "console.log('Hello');");

readFile()

Read a file from the virtual filesystem.
readFile(filePath: string): string | undefined
Returns: File contents or undefined if not found. Example:
const content = vfs.readFile("package.json");
if (content) {
  const pkg = JSON.parse(content);
  console.log(pkg.name);
}

exists()

Check if a path exists.
exists(path: string): boolean
Example:
if (vfs.exists("src/index.ts")) {
  console.log("File exists");
}

fileExists()

Check if a file exists.
fileExists(filePath: string): boolean
Example:
if (vfs.fileExists("package.json")) {
  console.log("package.json found");
}

directoryExists()

Check if a directory exists.
directoryExists(dirPath: string): boolean
Example:
if (vfs.directoryExists("src")) {
  console.log("src directory exists");
}

mkdir()

Create a directory (recursive).
mkdir(dirPath: string): void
Example:
vfs.mkdir("src/components/ui");

deleteFile()

Delete a file.
deleteFile(filePath: string): boolean
Returns: true if deleted, false if not found. Example:
if (vfs.deleteFile("old-file.ts")) {
  console.log("Deleted");
}

listDir()

List directory contents.
listDir(dirPath: string): string[]
Returns: Array of file/directory names (sorted). Example:
const files = vfs.listDir("src");
console.log("Files in src:", files);

readJson()

Read and parse a JSON file.
readJson<T = unknown>(filePath: string): T | undefined
Example:
interface PackageJson {
  name: string;
  version: string;
}

const pkg = vfs.readJson<PackageJson>("package.json");
if (pkg) {
  console.log(`${pkg.name}@${pkg.version}`);
}

writeJson()

Write a JSON file.
writeJson(filePath: string, data: unknown, spaces = 2): void
Example:
vfs.writeJson("package.json", {
  name: "my-app",
  version: "1.0.0",
});

getAllFiles()

Get all file paths.
getAllFiles(): string[]
Returns: Sorted array of all file paths. Example:
const files = vfs.getAllFiles();
console.log(`Total files: ${files.length}`);
files.forEach(file => console.log(file));

getAllDirectories()

Get all directory paths.
getAllDirectories(): string[]
Returns: Sorted array of all directory paths (excluding root /). Example:
const dirs = vfs.getAllDirectories();
console.log(`Total directories: ${dirs.length}`);

getFileCount()

Get total number of files.
getFileCount(): number
Example:
console.log(`Files: ${vfs.getFileCount()}`);

getDirectoryCount()

Get total number of directories.
getDirectoryCount(): number
Example:
console.log(`Directories: ${vfs.getDirectoryCount()}`);

toTree()

Convert to a tree structure.
toTree(rootName = "project"): VirtualDirectory
Returns: VirtualDirectory root node with all children. Example:
const tree = vfs.toTree("my-app");
console.log(`Root: ${tree.name}`);
console.log(`Children: ${tree.children.length}`);

clear()

Clear all files and directories.
clear(): void
Example:
vfs.clear();
console.log(`Files: ${vfs.getFileCount()}`); // 0

getVolume() / getFs()

Get the underlying memfs volume or fs instance.
getVolume(): Volume
getFs(): IFs
Example:
const vol = vfs.getVolume();
const fs = vfs.getFs();

Examples

Basic Usage

import { VirtualFileSystem } from "create-better-t-stack";

const vfs = new VirtualFileSystem();

// Write files
vfs.writeFile("package.json", JSON.stringify({
  name: "my-app",
  version: "1.0.0",
}, null, 2));

vfs.writeFile("src/index.ts", `
console.log('Hello World');
`);

vfs.writeFile("src/utils/helper.ts", `
export function hello() {
  return 'Hello';
}
`);

// Read files
const indexContent = vfs.readFile("src/index.ts");
console.log(indexContent);

// List files
const allFiles = vfs.getAllFiles();
console.log(`Total files: ${allFiles.length}`);
allFiles.forEach(f => console.log(f));

Working with JSON

import { VirtualFileSystem } from "create-better-t-stack";

const vfs = new VirtualFileSystem();

// Write JSON
vfs.writeJson("config.json", {
  app: "my-app",
  port: 3000,
});

// Read JSON
const config = vfs.readJson<{ app: string; port: number }>("config.json");
if (config) {
  console.log(`App: ${config.app} on port ${config.port}`);
}

// Modify and write back
if (config) {
  config.port = 4000;
  vfs.writeJson("config.json", config);
}

Directory Operations

import { VirtualFileSystem } from "create-better-t-stack";

const vfs = new VirtualFileSystem();

// Create directories
vfs.mkdir("src/components");
vfs.mkdir("src/utils");
vfs.mkdir("src/hooks");

// Write files in directories
vfs.writeFile("src/components/Button.tsx", "export const Button = ...");
vfs.writeFile("src/utils/format.ts", "export function format(...)");

// List directory contents
const srcFiles = vfs.listDir("src");
console.log("src contains:", srcFiles);

// Check existence
if (vfs.directoryExists("src/components")) {
  console.log("components directory exists");
}

Converting to Tree Structure

import { VirtualFileSystem } from "create-better-t-stack";

const vfs = new VirtualFileSystem();

vfs.writeFile("package.json", "{}");
vfs.writeFile("src/index.ts", "...");
vfs.writeFile("src/utils/helper.ts", "...");

const tree = vfs.toTree("my-app");

function printTree(node, depth = 0) {
  const indent = "  ".repeat(depth);
  
  if (node.type === "directory") {
    console.log(`${indent}📁 ${node.name}/`);
    node.children.forEach(child => printTree(child, depth + 1));
  } else {
    console.log(`${indent}📄 ${node.name}`);
  }
}

printTree(tree);

Testing File Generation

import { describe, expect, test } from "bun:test";
import { VirtualFileSystem } from "create-better-t-stack";

describe("VirtualFileSystem", () => {
  test("writes and reads files", () => {
    const vfs = new VirtualFileSystem();
    
    vfs.writeFile("test.txt", "Hello World");
    
    expect(vfs.fileExists("test.txt")).toBe(true);
    expect(vfs.readFile("test.txt")).toBe("Hello World");
  });
  
  test("creates nested directories", () => {
    const vfs = new VirtualFileSystem();
    
    vfs.writeFile("a/b/c/file.txt", "content");
    
    expect(vfs.directoryExists("a")).toBe(true);
    expect(vfs.directoryExists("a/b")).toBe(true);
    expect(vfs.directoryExists("a/b/c")).toBe(true);
    expect(vfs.fileExists("a/b/c/file.txt")).toBe(true);
  });
  
  test("counts files and directories", () => {
    const vfs = new VirtualFileSystem();
    
    vfs.writeFile("file1.txt", "");
    vfs.writeFile("dir/file2.txt", "");
    vfs.writeFile("dir/subdir/file3.txt", "");
    
    expect(vfs.getFileCount()).toBe(3);
    expect(vfs.getDirectoryCount()).toBe(2); // dir, dir/subdir
  });
});

File Manipulation

import { VirtualFileSystem } from "create-better-t-stack";

const vfs = new VirtualFileSystem();

// Write initial file
vfs.writeFile("config.json", JSON.stringify({ version: 1 }, null, 2));

// Read and modify
const config = vfs.readJson<{ version: number }>("config.json");
if (config) {
  config.version = 2;
  vfs.writeJson("config.json", config);
}

// Create backup
const content = vfs.readFile("config.json");
if (content) {
  vfs.writeFile("config.backup.json", content);
}

// Delete original
vfs.deleteFile("config.json");

console.log("Files:", vfs.getAllFiles());
// ["config.backup.json"]

Use Cases

Testing

Test file generation without disk I/O

Web Previews

Generate and display files in browser

Analysis

Analyze generated project structure

Templating

Build custom template processors

Notes

All paths are automatically normalized and prefixed with / internally.
The VirtualFileSystem is isolated - multiple instances don’t share state.
The VirtualFileSystem stores everything in memory. Very large projects may consume significant RAM.

Build docs developers (and LLMs) love