Package Exports
- opfs-enhanced
- opfs-enhanced/dist/opfs-enhanced.es.js
- opfs-enhanced/dist/opfs-enhanced.umd.js
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (opfs-enhanced) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
OPFS Enhanced ๐๏ธ
A modern TypeScript library for browser-based file system operations using OPFS (Origin Private File System)
โจ Features
- ๐ Modern API: Built on the latest OPFS standard, providing powerful browser file system operations
- ๐ Complete Functionality: Supports file reading/writing, directory operations, file copying/moving, and more
- ๐ฏ TypeScript: Fully written in TypeScript with complete type support
- ๐ก๏ธ Error Handling: Comprehensive error handling with user-friendly error messages
- ๐ง Easy to Use: API designed similar to fs-extra, reducing learning curve
- โก High Performance: Utilizes native browser OPFS API for excellent performance
- ๐ Browser Compatible: Supports OPFS functionality in modern browsers
๐ Quick Start
Installation
npm install opfs-enhanced
Basic Usage
import { FileSystem } from 'opfs-enhanced';
// Write file
await FileSystem.writeFile('hello.txt', 'Hello, World!');
// Read file
const content = await FileSystem.readFile('hello.txt');
console.log(content); // 'Hello, World!'
// Create directory
await FileSystem.ensureDir('my-folder');
// List directory contents
const files = await FileSystem.readdir('my-folder');
// Copy file
await FileSystem.copy('hello.txt', 'my-folder/hello-copy.txt');
// Move file
await FileSystem.move('hello.txt', 'my-folder/hello.txt');
// JSON operations
const data = { name: 'File Vault', version: '1.0.0' };
await FileSystem.writeJson('package.json', data);
const json = await FileSystem.readJson('package.json');
Demo Application
A complete file manager web application is included in the examples/
directory to demonstrate the library's capabilities. To run the demo:
npm install
npm run dev
Then open http://localhost:3000 to see the file manager in action.
๐๏ธ Project Structure
opfs-enhanced/
โโโ src/ # TypeScript source code
โ โโโ index.ts # Main library entry point
โ โโโ types.ts # Type definitions
โ โโโ core/ # Core functionality
โ โ โโโ filesystem.ts # File system operations
โ โโโ utils/ # Utility functions
โ โโโ errors.ts # Error handling
โ โโโ path.ts # Path utilities
โโโ examples/ # Demo applications
โ โโโ web/ # Web file manager demo
โ โโโ styles/ # Demo CSS files
โ โโโ scripts/ # Demo JavaScript files
โโโ tests/ # Test files
โโโ doc/ # Documentation
โโโ index.html # Demo application entry point
โโโ package.json # Project configuration
โโโ tsconfig.json # TypeScript configuration
โโโ vite.config.ts # Vite build configuration
โโโ README.md # This file
๐ API Documentation
File Operations
writeFile(path: string, data: string | ArrayBuffer | Uint8Array, options?: WriteOptions): Promise<void>
Write content to a file.
// Write text file
await FileSystem.writeFile('note.txt', 'This is a note');
// Write binary file
const buffer = new Uint8Array([72, 101, 108, 108, 111]);
await FileSystem.writeFile('data.bin', buffer);
readFile(path: string, encoding?: string): Promise<string>
Read file content as string.
const content = await FileSystem.readFile('note.txt');
readFileBuffer(path: string): Promise<ArrayBuffer>
Read file content as ArrayBuffer.
const buffer = await FileSystem.readFileBuffer('data.bin');
exists(path: string): Promise<boolean>
Check if file or directory exists.
const fileExists = await FileSystem.exists('note.txt');
stat(path: string): Promise<OPFSStats>
Get file or directory statistics.
const stats = await FileSystem.stat('note.txt');
console.log(stats.size, stats.lastModified, stats.kind);
remove(path: string): Promise<void>
Delete file or directory.
await FileSystem.remove('note.txt');
await FileSystem.remove('my-folder'); // Recursively delete directory
Directory Operations
mkdir(path: string, options?: EnsureOptions): Promise<void>
Create directory.
await FileSystem.mkdir('new-folder');
await FileSystem.mkdir('deep/nested/folder', { recursive: true });
ensureDir(path: string): Promise<void>
Ensure directory exists, create if it doesn't.
await FileSystem.ensureDir('path/to/folder');
readdir(path: string): Promise<string[]>
List directory contents.
const files = await FileSystem.readdir('my-folder');
console.log(files); // ['file1.txt', 'file2.txt', 'subfolder']
File Copy and Move Operations
copy(src: string, dest: string, options?: CopyOptions): Promise<void>
Copy file or directory.
// Copy file
await FileSystem.copy('source.txt', 'destination.txt');
// Copy directory
await FileSystem.copy('source-folder', 'dest-folder');
// Copy with options
await FileSystem.copy('source.txt', 'dest.txt', {
overwrite: true,
filter: (src, dest) => !src.endsWith('.tmp')
});
move(src: string, dest: string, options?: MoveOptions): Promise<void>
Move file or directory.
await FileSystem.move('old-name.txt', 'new-name.txt');
await FileSystem.move('folder', 'new-location/folder');
JSON Operations
readJson(path: string, options?: ReadJsonOptions): Promise<any>
Read JSON file.
const data = await FileSystem.readJson('config.json');
// With options
const data = await FileSystem.readJson('config.json', {
throws: false, // Return null instead of throwing error when file doesn't exist
reviver: (key, value) => key === 'date' ? new Date(value) : value
});
writeJson(path: string, data: any, options?: WriteJsonOptions): Promise<void>
Write JSON file.
const data = { name: 'example', values: [1, 2, 3] };
await FileSystem.writeJson('data.json', data);
// With options
await FileSystem.writeJson('data.json', data, {
spaces: 4, // Number of spaces for indentation
replacer: (key, value) => typeof value === 'bigint' ? value.toString() : value
});
Directory Traversal
walk(path: string, options?: WalkOptions): AsyncGenerator<FileInfo>
Recursively traverse directory.
// Traverse all files
for await (const file of FileSystem.walk('my-folder')) {
console.log(file.path, file.kind, file.size);
}
// Traverse with options
for await (const item of FileSystem.walk('my-folder', {
includeDirs: true, // Include directories
maxDepth: 2, // Maximum depth
filter: (path, info) => info.kind === 'file' && path.endsWith('.txt')
})) {
console.log(item.path);
}
๐ง Advanced Usage
Error Handling
import { FileSystemError, FileSystemErrorCode } from 'opfs-enhanced';
try {
await FileSystem.readFile('non-existent.txt');
} catch (error) {
if (error instanceof FileSystemError) {
switch (error.code) {
case FileSystemErrorCode.FILE_NOT_FOUND:
console.log('File not found');
break;
case FileSystemErrorCode.PERMISSION_DENIED:
console.log('Permission denied');
break;
default:
console.log('Other error:', error.message);
}
}
}
Path Operations
import { dirname, basename, extname, joinPath } from 'opfs-enhanced';
const filePath = 'documents/projects/readme.md';
console.log(dirname(filePath)); // 'documents/projects'
console.log(basename(filePath)); // 'readme.md'
console.log(extname(filePath)); // '.md'
const newPath = joinPath('assets', 'images', 'logo.png');
console.log(newPath); // 'assets/images/logo.png'
๐ฏ Use Cases
1. Local Data Storage
// Save user settings
const userSettings = {
theme: 'dark',
language: 'en-US',
autoSave: true
};
await FileSystem.writeJson('settings.json', userSettings);
// Read user settings
const settings = await FileSystem.readJson('settings.json');
2. File Editor
// Save document
await FileSystem.writeFile('documents/my-doc.md', documentContent);
// Create project structure
await FileSystem.ensureDir('project/src');
await FileSystem.ensureDir('project/assets');
await FileSystem.writeFile('project/README.md', '# My Project');
3. Cache Management
// Cache data
const cacheData = { data: results, timestamp: Date.now() };
await FileSystem.writeJson('cache/api-results.json', cacheData);
// Clean expired cache
for await (const file of FileSystem.walk('cache')) {
const stats = await FileSystem.stat(file.path);
if (Date.now() - stats.lastModified > 24 * 60 * 60 * 1000) {
await FileSystem.remove(file.path);
}
}
4. Backup Tool
// Create backup
const backupFolder = `backup-${new Date().toISOString().split('T')[0]}`;
await FileSystem.ensureDir(backupFolder);
await FileSystem.copy('important-data', `${backupFolder}/important-data`);
๐ Browser Support
Browser | Version | Support |
---|---|---|
Chrome | 86+ | โ Full |
Firefox | 111+ | โ Full |
Safari | 15.2+ | โ Full |
Edge | 86+ | โ Full |
Note: OPFS requires a secure context (HTTPS or localhost)
๐ง Limitations
- Browser Support: Requires modern browsers with OPFS support
- Secure Context: Must be used in HTTPS or localhost environment
- Storage Space: Limited by browser storage quota
- Cross-Domain: Data is stored per domain, cannot be accessed across domains
๐งช Development Guide
Project Setup
# Clone project
git clone <repository-url>
cd opfs-enhanced
# Install dependencies
npm install
# Development
npm run dev
# Build
npm run build
# Test
npm test
# Run demo
npm run preview
Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature
) - Commit your changes (
git commit -m 'Add some amazing feature'
) - Push to the branch (
git push origin feature/amazing-feature
) - Open a Pull Request
Testing
# Run all tests
npm test
# Run tests in watch mode
npm run test:watch
# Run tests with coverage
npm run test:coverage
๐ License
This project is licensed under the MIT License - see the LICENSE file for details.
๐ Acknowledgments
- OPFS API - For providing browser file system access
- TypeScript - For excellent type safety
- Vite - For fast development and building
- Biome - For code formatting and linting
- fs-extra - For API inspiration
๐ค Support
If you have any questions or need help, please:
- Check the documentation
- Search existing issues
- Create a new issue
Made with โค๏ธ by the File Vault team