### Install @jsonjoy.com/fs-snapshot Source: https://github.com/streamich/memfs/blob/master/packages/fs-snapshot/README.md Install the package using npm. ```bash npm install @jsonjoy.com/fs-snapshot ``` -------------------------------- ### Install fs-print Source: https://github.com/streamich/memfs/blob/master/packages/fs-print/README.md Install the package using npm. ```bash npm install @jsonjoy.com/fs-print ``` -------------------------------- ### Install @jsonjoy.com/fs-core Source: https://github.com/streamich/memfs/blob/master/packages/fs-core/README.md Install the package using npm. ```bash npm install @jsonjoy.com/fs-core ``` -------------------------------- ### Install @jsonjoy.com/fs-node-to-fsa Source: https://github.com/streamich/memfs/blob/master/packages/fs-node-to-fsa/README.md Install the package using npm. ```bash npm install @jsonjoy.com/fs-node-to-fsa ``` -------------------------------- ### Install @jsonjoy.com/fs-fsa-to-node Source: https://github.com/streamich/memfs/blob/master/packages/fs-fsa-to-node/README.md Install the package using npm. ```bash npm install @jsonjoy.com/fs-fsa-to-node ``` -------------------------------- ### Usage Example for @jsonjoy.com/fs-fsa Source: https://github.com/streamich/memfs/blob/master/packages/fs-fsa/README.md Demonstrates creating and reading a file using the File System Access API. ```typescript import { fsa } from '@jsonjoy.com/fs-fsa'; const { dir, core, FileSystemObserver } = fsa({ mode: 'readwrite' }); // Create a file const fileHandle = await dir.getFileHandle('hello.txt', { create: true }); const writable = await fileHandle.createWritable(); await writable.write('Hello, World!'); await writable.close(); // Read a file const file = await fileHandle.getFile(); const contents = await file.text(); console.log(contents); // 'Hello, World!' ``` -------------------------------- ### Install @jsonjoy.com/fs-fsa Source: https://github.com/streamich/memfs/blob/master/packages/fs-fsa/README.md Install the package using npm. ```bash npm install @jsonjoy.com/fs-fsa ``` -------------------------------- ### Browser File System API Quick Start Source: https://github.com/streamich/memfs/blob/master/packages/memfs/README.md Demonstrates basic file system operations using the browser File System Access API with memfs. Import the `fsa` object from 'memfs' to interact with the file system. ```javascript import { fsa } from 'memfs'; // Get root directory handle const root = await fsa.getRoot(); // Create a file const file = await root.getFileHandle('hello.txt', { create: true }); const writable = await file.createWritable(); await writable.write('Hello, World!'); await writable.close(); // Read the file const readable = await file.getFile(); const text = await readable.text(); console.log(text); // "Hello, World!" ``` -------------------------------- ### Install @jsonjoy.com/fs-node Source: https://github.com/streamich/memfs/blob/master/packages/fs-node/README.md Install the package using npm. ```bash npm install @jsonjoy.com/fs-node ``` -------------------------------- ### Install Dependencies Source: https://github.com/streamich/memfs/blob/master/CONTRIBUTING.md Run this command to install all project dependencies using Yarn. ```bash yarn ``` -------------------------------- ### Node.js fs API Quick Start Source: https://github.com/streamich/memfs/blob/master/packages/memfs/README.md Demonstrates basic file system operations using the Node.js fs API with memfs. Import the `fs` object from 'memfs' to use its methods. ```javascript import { fs } from 'memfs'; // Write a file fs.writeFileSync('/hello.txt', 'Hello, World!'); // Read a file const content = fs.readFileSync('/hello.txt', 'utf-8'); console.log(content); // "Hello, World!" // Create a directory fs.mkdirSync('/mydir'); // List directory contents console.log(fs.readdirSync('/')); // ['hello.txt', 'mydir'] ``` -------------------------------- ### Usage Example for @jsonjoy.com/fs-fsa-to-node Source: https://github.com/streamich/memfs/blob/master/packages/fs-fsa-to-node/README.md Import and instantiate FsaNodeFs with a FileSystemDirectoryHandle. Then use familiar Node.js fs promises API for file operations. ```typescript import { FsaNodeFs } from '@jsonjoy.com/fs-fsa-to-node'; // Get a FileSystemDirectoryHandle (e.g., from showDirectoryPicker()) const dirHandle = await window.showDirectoryPicker(); // Create a Node.js fs-like API from the directory handle const fs = new FsaNodeFs(dirHandle); // Use familiar Node.js fs API await fs.promises.writeFile('/test.txt', 'Hello, World!'); const content = await fs.promises.readFile('/test.txt', 'utf8'); console.log(content); // 'Hello, World!' ``` -------------------------------- ### Run isomorphic-git on memfs Demo Source: https://github.com/streamich/memfs/blob/master/packages/memfs/demo/git/README.md Execute the demo using yarn and ts-node. This command installs dependencies and runs the TypeScript demo file. ```bash yarn npx ts-node demo/git/index.ts ``` -------------------------------- ### Install memfs Source: https://github.com/streamich/memfs/blob/master/README.md Install the memfs package using npm. ```shell npm i memfs ``` -------------------------------- ### Use FSA FileSystemDirectoryHandle as Node.js fs (Async API) Source: https://context7.com/streamich/memfs/llms.txt Wraps a FileSystemDirectoryHandle as a Node.js-compatible fs object for use in the browser. Requires no special setup for the async API. ```typescript import { FsaNodeFs } from 'memfs/lib/fsa-to-node'; import { fsa } from 'memfs/lib/fsa'; // --- Async API (works out of the box) --- const { dir } = fsa({ mode: 'readwrite' }); const fs = new FsaNodeFs(dir); await fs.promises.mkdir('/output', { recursive: true }); await fs.promises.writeFile('/output/result.json', JSON.stringify({ status: 'ok' })); const data = await fs.promises.readFile('/output/result.json', 'utf8'); console.log(data); // => '{"status":"ok"}' // Write stream const stream = fs.createWriteStream('/output/log.txt'); stream.write('entry 1\n'); stream.write('entry 2\n'); await new Promise(resolve => stream.end(resolve)); console.log(await fs.promises.readFile('/output/log.txt', 'utf8')); // => 'entry 1\nentry 2\n' ``` -------------------------------- ### Run Demo Command Source: https://github.com/streamich/memfs/blob/master/packages/memfs/demo/fsa-to-node-sync-tests/README.md Execute the demo for fsa-to-node-sync-tests. ```bash demo:fsa-to-node-sync-tests ``` -------------------------------- ### Run Demo: fsa-to-node-zipfile Source: https://github.com/streamich/memfs/blob/master/packages/memfs/demo/fsa-to-node-zipfile/README.md Execute the demo script to see the File System Access API and tar-stream integration in action. ```bash demo:fsa-to-node-zipfile ``` -------------------------------- ### Prepare for Release Source: https://github.com/streamich/memfs/blob/master/scripts/RELEASE.md Commands to clean the project and build the distributable artifacts. ```bash yarn clean ``` ```bash yarn build ``` -------------------------------- ### Volume Class Initialization Source: https://github.com/streamich/memfs/blob/master/packages/fs-node/README.md Demonstrates how to create a new in-memory filesystem instance using the Volume class. ```APIDOC ## new Volume() ### Description Creates a new, empty in-memory filesystem. ### Usage ```ts import { Volume } from '@jsonjoy.com/fs-node'; const vol = new Volume(); ``` ``` -------------------------------- ### Put, Get, and Delete Blobs with `casfs` Source: https://github.com/streamich/memfs/blob/master/docs/casfs/index.md Demonstrates the core `casfs` operations: `put` to store a blob and get its hash, `get` to retrieve a blob by its hash, and `del` to remove a blob. The `put` operation returns the content hash. ```js const blob = new Uint8Array([1, 2, 3]); const hash = await cas.put(blob); console.log(hash); // 9dc58b6d4e8eefb5a3c3e0c9f4a1a0b1b2b3b4b5 const blob2 = await cas.get(hash); await cas.del(hash); ``` -------------------------------- ### Volume Constructor and Volume.fromJSON Source: https://context7.com/streamich/memfs/llms.txt Demonstrates how to create independent in-memory file system instances using the Volume constructor and initialize them from a flat JSON object using Volume.fromJSON. ```APIDOC ## `Volume` constructor and `Volume.fromJSON` `Volume` is the constructor for creating independent in-memory file system instances. Multiple volumes can coexist without interference. Use `Volume.fromJSON` for convenient one-liner initialization from a flat path→content map. ```ts import { Volume } from 'memfs'; // Construct from flat JSON (keys are absolute paths) const vol = Volume.fromJSON({ '/etc/hosts': '127.0.0.1 localhost', '/etc/resolv.conf': 'nameserver 8.8.8.8', '/home/user/.bashrc': 'export PATH=$PATH:/usr/local/bin', }); vol.readFileSync('/etc/hosts', 'utf8'); // => '127.0.0.1 localhost' // Multiple independent volumes const vol2 = Volume.fromJSON({ '/tmp/data.txt': 'volume 2' }); vol2.readFileSync('/tmp/data.txt', 'utf8'); // => 'volume 2' vol.existsSync('/tmp/data.txt'); // => false // fromJSON with a base directory (relative keys resolved against it) const vol3 = new Volume(); vol3.fromJSON( { './index.js': 'export default 42', './package.json': '{"type":"module"}', }, '/project', ); vol3.readFileSync('/project/index.js', 'utf8'); // => 'export default 42' ``` ``` -------------------------------- ### Retrieve Resource Content with FsaCrud Source: https://github.com/streamich/memfs/blob/master/docs/crudfs/index.md Fetch the content of a specific resource (file) from a collection using the `get` method. ```javascript const file1 = await crud.get(['user', 'files'], 'file1.bin'); ``` -------------------------------- ### Content-Addressable Storage with `CrudCas` Source: https://context7.com/streamich/memfs/llms.txt Builds on `crudfs` to provide a hash-addressed blob store that automatically deduplicates identical content. Supports `put`, `get`, `del`, and `info` operations. ```typescript import { createHash } from 'crypto'; import { memfs } from 'memfs'; import { nodeToFsa } from 'memfs/lib/node-to-fsa'; import { FsaCrud } from 'memfs/lib/fsa-to-crud'; import { CrudCas } from 'memfs/lib/cas'; // Hash function: SHA-1 of the blob const hash = async (blob: Uint8Array): Promise => { const shasum = createHash('sha1'); shasum.update(blob); return shasum.digest('hex'); }; // Build the stack: memfs → FSA → crudfs → casfs const { fs } = memfs({}, '/'); const dir = nodeToFsa(fs, '/', { mode: 'readwrite' }); const crud = new FsaCrud(dir); const cas = new CrudCas(crud, { hash }); // Store a blob const blob = new TextEncoder().encode('Hello, CAS!'); const digest = await cas.put(blob); console.log(digest); // => 'e.g. 4b7f3c2a...' (SHA-1 of blob) // Retrieve by hash const fetched = await cas.get(digest); console.log(new TextDecoder().decode(fetched)); // => 'Hello, CAS!' // Identical content deduplicates (same hash returned) const digest2 = await cas.put(blob); console.log(digest === digest2); // => true // Info about a blob const info = await cas.info(digest); console.log(info); // => { size: 11 } (or similar metadata) // Delete by hash await cas.del(digest); try { await cas.get(digest); } catch (e) { console.log(e.message); // => Not found } ``` -------------------------------- ### Customizing fs-print Output Source: https://github.com/streamich/memfs/blob/master/packages/fs-print/README.md Customize the tree output by providing an options object to `toTreeSync`. Options include starting directory, depth, path separator, indentation, and sorting. ```typescript toTreeSync(fs, { dir: '/src', // Starting directory (default: '/') depth: 2, // Maximum depth to traverse (default: 10) separator: '/', // Path separator (default: '/') tab: ' ', // Indentation string (default: '') sort: true, // Sort entries (default: true) }); ``` -------------------------------- ### Create and Initialize Filesystem Source: https://github.com/streamich/memfs/blob/master/packages/fs-core/README.md Create a new in-memory filesystem or initialize one from a JSON structure. ```typescript import { Superblock, DirectoryJSON } from '@jsonjoy.com/fs-core'; // Create a new filesystem const fs = new Superblock(); // Or create from a JSON structure const json: DirectoryJSON = { '/file.txt': 'Hello, World!', '/dir/nested.txt': 'Nested content', }; const fs = Superblock.fromJSON(json); ``` -------------------------------- ### Testing with Memfs Source: https://github.com/streamich/memfs/blob/master/docs/node/usage.md Shows how to use `memfs` for testing by writing a file and then asserting the file system's state using `vol.toJSON()` and `expect`. ```javascript vol.writeFileSync('/foo', 'bar'); expect(vol.toJSON()).toEqual({ '/foo': 'bar' }); ``` -------------------------------- ### Run Git FSA Demo Source: https://github.com/streamich/memfs/blob/master/packages/memfs/demo/git-fsa/README.md Execute the demo to see Git commands run in the browser against a user-selected folder via the File System Access API. ```bash yarn demo:git-fsa ``` -------------------------------- ### Initialize `casfs` with Node.js `fs` Source: https://github.com/streamich/memfs/blob/master/docs/casfs/index.md Sets up a `casfs` instance using Node.js's `fs` module, converting it to a File System Access API compatible interface. Ensure the path exists and has read/write permissions. ```js import * as fs from 'fs'; import { nodeToFsa } from 'memfs/lib/node-to-fsa'; import { FsaCrud } from 'memfs/lib/fsa-to-crud'; const fsa = nodeToFsa(fs, '/path/to/folder', { mode: 'readwrite' }); const crud = new FsaCrud(fsa); const cas = new CrudCas(crud, { hash }); ``` -------------------------------- ### Volume.fromJSON Static Method Source: https://github.com/streamich/memfs/blob/master/packages/fs-node/README.md Shows how to initialize an in-memory filesystem with pre-defined content from a JSON object. ```APIDOC ## Volume.fromJSON(json: Record) ### Description Creates a new in-memory filesystem populated with the content specified in the JSON object. ### Usage ```ts import { Volume } from '@jsonjoy.com/fs-node'; const vol = Volume.fromJSON({ '/app/index.js': 'console.log("Hello");', '/app/package.json': '{"name": "app"}', }); ``` ``` -------------------------------- ### Creating Multiple Memfs Volumes Source: https://github.com/streamich/memfs/blob/master/docs/node/usage.md Demonstrates creating multiple independent file system volumes using `Volume.fromJSON`. Each volume can be initialized with different content. ```javascript import { Volume } from 'memfs'; const vol = Volume.fromJSON({ '/foo': 'bar' }); vol.readFileSync('/foo'); // bar const vol2 = Volume.fromJSON({ '/foo': 'bar 2' }); vol2.readFileSync('/foo'); // bar 2 ``` -------------------------------- ### Basic File System Operations with Memfs Source: https://github.com/streamich/memfs/blob/master/docs/node/usage.md Demonstrates basic file system operations like writing and reading files using the `fs` object from `memfs`. Ensure `memfs` is imported. ```javascript import { fs } from 'memfs'; fs.writeFileSync('/hello.txt', 'World!'); fs.readFileSync('/hello.txt', 'utf8'); // World! ``` -------------------------------- ### Create and Use In-Memory FSA Filesystem Source: https://github.com/streamich/memfs/blob/master/docs/fsa/fsa.md Demonstrates creating a new in-memory filesystem, creating a directory and file, writing content to the file, and exporting the filesystem state to JSON. Requires 'readwrite' mode. ```typescript import { fsa } from 'memfs/lib/fsa'; // Create a new filesystem. const { dir, core } = fsa({ mode: 'readwrite' }); // Create a folder and a file. const dir2 = await dir.getDirectoryHandle('new-folder', { create: true }); const file = await dir2.getFileHandle('file.txt', { create: true }); await (await file.createWritable()).write('Hello, world!'); // Export whole filesystem to JSON. console.log(core.toJSON()); // { '/new-folder/file.txt': 'Hello, world!' } ``` -------------------------------- ### Build All Packages Source: https://github.com/streamich/memfs/blob/master/CONTRIBUTING.md Use this command to build all packages within the monorepo. ```bash yarn build ``` -------------------------------- ### Create a New File using FSA Directory Handle Source: https://github.com/streamich/memfs/blob/master/docs/fsa/fs-to-fsa.md Use the obtained directory handle to create a new file. The `create: true` option ensures the file is created if it doesn't exist. ```javascript const file = await dir.getFileHandle('foo.txt', { create: true }); ``` -------------------------------- ### Login to NPM Source: https://github.com/streamich/memfs/blob/master/scripts/RELEASE.md Authenticate with the NPM registry using your credentials. ```bash yarn npm login ``` -------------------------------- ### Volume Constructor Source: https://github.com/streamich/memfs/blob/master/docs/node/reference.md Demonstrates how to create a new in-memory file system volume using the Volume constructor. ```APIDOC ## `Volume` Constructor `Volume` is a constructor function for creating new volumes: ```js import { Volume } from 'memfs'; const vol = new Volume(); ``` `Volume` implements all [Node's filesystem methods](https://nodejs.org/api/fs.html): ```js vol.writeFileSync('/foo', 'bar'); ``` But it does not hold constants and its methods are not bound to `vol`: ```js vol.F_OK; // undefined ``` A new volume can be create using the `Volume.fromJSON` convenience method: ```js const vol = Volume.fromJSON({ '/app/index.js': '...', '/app/package.json': '...', }); ``` It is just a shorthand for `vol.fromJSON`, see below. ``` -------------------------------- ### Create In-Memory FSA Filesystem from JSON Source: https://github.com/streamich/memfs/blob/master/docs/fsa/fsa.md Shows how to initialize an in-memory filesystem from a JSON object, including nested structures and binary data. It then demonstrates accessing imported files and directories. ```typescript const { dir, core } = fsa({ mode: 'readwrite' }); // Import JSON. core.fromJSON( { 'documents/readme.txt': 'Welcome!', 'photos/vacation.jpg': Buffer.from('fake-jpg-data'), 'empty-folder': null, }, '/', ); // Use FSA API. const dir2 = await dir.getDirectoryHandle('documents'); const file = await dir2.getFileHandle('readme.txt'); const fileContent = await file.getFile(); console.log(await fileContent.text()); // 'Welcome!' ``` -------------------------------- ### Initialize FsaNodeFs with Synchronous API Source: https://github.com/streamich/memfs/blob/master/docs/fsa/fsa-to-fs.md Set up a synchronous filesystem adapter for FsaNodeFs using a worker. This requires the app to be served over HTTPS with COI enabled. ```javascript import { FsaNodeFs, FsaNodeSyncAdapterWorker } from 'memfs/lib/fsa-to-node'; const adapter = await FsaNodeSyncAdapterWorker.start('https:///worker.js', dir); const fs = new FsaNodeFs(dir, adapter); ``` -------------------------------- ### Import Snapshot Utilities Source: https://github.com/streamich/memfs/blob/master/docs/snapshot/index.md Import all necessary snapshot utility functions from the memfs library. This is the first step before using any snapshot functionality. ```typescript import * as snapshot from 'memfs/lib/snapshot'; ``` -------------------------------- ### Run Git OPFS Demo Source: https://github.com/streamich/memfs/blob/master/packages/memfs/demo/git-opfs/README.md Execute the demo script to run Git operations using memfs and OPFS in your browser. ```bash yarn demo:git-opfs ``` -------------------------------- ### Initialize FsaNodeFs with Async API Source: https://github.com/streamich/memfs/blob/master/docs/fsa/fsa-to-fs.md Instantiate FsaNodeFs with a FileSystemDirectoryHandle to use Node's fs API asynchronously. ```javascript import { FsaNodeFs } from 'memfs/lib/fsa-to-node'; const fs = new FsaNodeFs(dir); ``` -------------------------------- ### Async File Operations with fs.promises Source: https://context7.com/streamich/memfs/llms.txt Demonstrates basic read/write, readdir with Dirent objects, FileHandle usage, async iterator watch, and copy/rename/symlink operations using the promises API. ```typescript import { memfs } from 'memfs'; const { fs } = memfs({ '/data/a.txt': 'hello', '/data/b.txt': 'world', }); // Basic read/write await fs.promises.writeFile('/data/c.txt', 'appended'); const c = await fs.promises.readFile('/data/c.txt', 'utf8'); console.log(c); // => 'appended' // readdir with Dirent objects const entries = await fs.promises.readdir('/data', { withFileTypes: true }); for (const entry of entries) { console.log(entry.name, entry.isFile()); // a.txt true, b.txt true, c.txt true } // FileHandle usage const fh = await fs.promises.open('/data/a.txt', 'r'); const buf = Buffer.alloc(5); await fh.read(buf, 0, 5, 0); console.log(buf.toString()); // => 'hello' await fh.close(); // Async iterator watch await fs.promises.mkdir('/watch-dir', { recursive: true }); const watcher = fs.promises.watch('/watch-dir'); fs.promises.writeFile('/watch-dir/new.txt', '').catch(() => {}); for await (const event of watcher) { console.log(event.eventType, event.filename); // => 'rename' 'new.txt' break; } // Copy, rename, symlink await fs.promises.copyFile('/data/a.txt', '/data/a-copy.txt'); await fs.promises.rename('/data/a-copy.txt', '/data/a-renamed.txt'); await fs.promises.symlink('/data/a.txt', '/data/a-link.txt'); const lstat = await fs.promises.lstat('/data/a-link.txt'); console.log(lstat.isSymbolicLink()); // => true ``` -------------------------------- ### Write file to Volume instance Source: https://github.com/streamich/memfs/blob/master/docs/node/reference.md Demonstrates writing content to a file within a `Volume` instance using `writeFileSync`. ```javascript vol.writeFileSync('/foo', 'bar'); ``` -------------------------------- ### Initialize FsaCrud via Node.js fs module and FSA adapter Source: https://github.com/streamich/memfs/blob/master/docs/crudfs/index.md Run crudfs on Node.js `fs` by first adapting it to the File System Access API using `nodeToFsa`, then initializing `FsaCrud`. ```javascript import * as fs from 'fs'; import { nodeToFsa } from 'memfs/lib/node-to-fsa'; import { FsaCrud } from 'memfs/lib/fsa-to-crud'; const dir = nodeToFsa(fs, '/path/to/folder', { mode: 'readwrite' }); const crud = new FsaCrud(dir); ``` -------------------------------- ### Import memfs vol and fs objects Source: https://github.com/streamich/memfs/blob/master/docs/node/reference.md Import the default `vol` instance and the `fs`-like object from `memfs`. `vol` is a `Volume` instance, and `fs` is created from `vol`. ```javascript import { vol, fs } from 'memfs'; ``` -------------------------------- ### vol.fromJSON and vol.toJSON Source: https://context7.com/streamich/memfs/llms.txt Explains how to populate an existing volume using `vol.fromJSON` with relative paths resolved against a base directory, and how to export the volume's contents to a JSON object using `vol.toJSON`. ```APIDOC ## `vol.fromJSON(json[, cwd])` and `vol.toJSON([paths[, json[, isRelative]]])` `fromJSON` populates an existing volume from a flat JSON object (relative paths resolved against `cwd`). `toJSON` exports the entire volume (or a subset of paths) to a flat JSON object — perfect for snapshot-based assertions in tests. ```ts import { Volume } from 'memfs'; const vol = new Volume(); // Populate vol.fromJSON( { './README.md': '# My Project', './src/index.ts': 'export const x = 1;', './src/types.ts': 'export type ID = string;', }, '/repo', ); // Export whole volume vol.toJSON(); // => { // '/repo/README.md': '# My Project', // '/repo/src/index.ts': 'export const x = 1;', // '/repo/src/types.ts': 'export type ID = string;' // } // Export only a subdirectory vol.toJSON(['/repo/src']); // => { // '/repo/src/index.ts': 'export const x = 1;', // '/repo/src/types.ts': 'export type ID = string;' // } // Relative keys in exported JSON vol.toJSON(['/repo/src'], {}, true); // => { 'index.ts': 'export const x = 1;', 'types.ts': 'export type ID = string;' } // Use in tests vol.writeFileSync('/repo/build/out.js', 'compiled'); expect(vol.toJSON(['/repo/build'], {}, true)).toEqual({ 'out.js': 'compiled' }); // Reset the volume vol.reset(); vol.toJSON(); // => {} ``` ``` -------------------------------- ### Create a new Volume instance Source: https://github.com/streamich/memfs/blob/master/docs/node/reference.md Instantiate a new `Volume` object to manage an in-memory filesystem. This `Volume` instance implements Node.js's filesystem methods. ```javascript import { Volume } from 'memfs'; const vol = new Volume(); ``` -------------------------------- ### Create FSA Directory Handle from Node `fs` Source: https://github.com/streamich/memfs/blob/master/docs/fsa/fs-to-fsa.md Instantiate a FileSystemDirectoryHandle from a Node.js fs object and a path. The `mode` option can be set to 'readwrite'. ```javascript import { nodeToFsa } from 'memfs/lib/node-to-fsa'; const dir = nodeToFsa(fs, '/path/to/folder', { mode: 'readwrite' }); ``` -------------------------------- ### POJO Snapshot Operations Source: https://github.com/streamich/memfs/blob/master/docs/snapshot/index.md Create and import POJO snapshots of a file system. ```APIDOC ## POJO Snapshot ### Create Snapshot Synchronously ```ts const snap = snapshot.toSnapshotSync({ fs, path }); ``` ### Create Snapshot Asynchronously ```ts const snap = await snapshot.toSnapshot({ fs: fs.promises, path }); ``` ### Import Snapshot Synchronously ```ts snapshot.fromSnapshotSync(snap, { fs, path }); ``` ### Import Snapshot Asynchronously ```ts await snapshot.fromSnapshot(snap, { fs: fs.promises, path }); ``` ``` -------------------------------- ### Volume Instance Methods Source: https://github.com/streamich/memfs/blob/master/docs/node/reference.md Reference for the methods available on a Volume instance, including file manipulation and export utilities. ```APIDOC ## `Volume` instance `vol` #### `vol.fromJSON(json[, cwd])` Adds files from a flat `json` object to the volume `vol`. The `cwd` argument is optional and is used to compute absolute file paths, if a file path is given in a relative form. **Note:** To remove all existing files, use `vol.reset()` method. ```js vol.fromJSON( { './index.js': '...', './package.json': '...', './index.node': new Buffer(), }, '/app', ); ``` #### `vol.mountSync(cwd, json)` Legacy method, which is just an alias for `vol.fromJSON`. #### `vol.toJSON([paths[, json[, isRelative]]])` Exports the whole contents of the volume recursively to a flat JSON object. `paths` is an optional argument that specifies one or more paths to be exported. If this argument is omitted, the whole volume is exported. `paths` can be an array of paths. A path can be a string, `Buffer` or an `URL` object. `json` is an optional object parameter which will be populated with the exported files. `isRelative` is boolean that specifies if returned paths should be relative. #### `vol.reset()` Removes all files from the volume. ```js vol.fromJSON({ '/index.js': '...' }); vol.toJSON(); // {'/index.js': '...' } vol.reset(); vol.toJSON(); // {} ``` #### `vol.toTree()` Returns a string representation of a volume folder contents as a tree. ```ts import { memfs } from 'memfs'; const { vol } = memfs({ '/Users/streamich/src/github/memfs/src': { 'package.json': '...', 'tsconfig.json': '...', 'index.ts': '...', util: { 'index.ts': '...', print: { 'index.ts': '...', 'printTree.ts': '...', }, }, }, }); console.log(vol.toTree()); // Output: // / // └─ Users/ // └─ streamich/ // └─ src/ // └─ github/ // └─ memfs/ // └─ src/ // ├─ index.ts // ├─ package.json // ├─ tsconfig.json // └─ util/ // ├─ index.ts // └─ print/ // ├─ index.ts // └─ printTree.ts ``` The `.toTree()` method accepts options object, where one can specify a sub-folder, depth of the printed tree, and a separator. ``` -------------------------------- ### Snapshot Utility Functions Source: https://github.com/streamich/memfs/blob/master/docs/snapshot/index.md Import and use various snapshot utility functions from the 'memfs/lib/snapshot' module. ```APIDOC ## Import Snapshot Utilities ```ts import * as snapshot from 'memfs/lib/snapshot'; ``` ### Available Functions - `snapshot.toSnapshotSync()`: Returns a POJO snapshot synchronously. - `snapshot.toSnapshot()`: Returns a POJO snapshot asynchronously. - `snapshot.fromSnapshotSync()`: Imports a POJO snapshot synchronously. - `snapshot.fromSnapshot()`: Imports a POJO snapshot asynchronously. - `snapshot.toBinarySnapshotSync()`: Returns a CBOR `Uint8Array` snapshot synchronously. - `snapshot.toBinarySnapshot()`: Returns a CBOR `Uint8Array` snapshot asynchronously. - `snapshot.fromBinarySnapshotSync()`: Imports a CBOR `Uint8Array` snapshot synchronously. - `snapshot.fromBinarySnapshot()`: Imports a CBOR `Uint8Array` snapshot asynchronously. - `snapshot.toJsonSnapshotSync()`: Returns a JSON `Uint8Array` snapshot synchronously. - `snapshot.toJsonSnapshot()`: Returns a JSON `Uint8Array` snapshot asynchronously. - `snapshot.fromJsonSnapshotSync()`: Imports a JSON `Uint8Array` snapshot synchronously. - `snapshot.fromJsonSnapshot()`: Imports a JSON `Uint8Array` snapshot asynchronously. ``` -------------------------------- ### Run Quick Release Script Source: https://github.com/streamich/memfs/blob/master/scripts/RELEASE.md Execute the interactive release script. Can specify a default (minor) bump, a specific bump type (patch, major), or an exact version number. ```bash ./scripts/quick-release.sh ``` ```bash ./scripts/quick-release.sh patch ``` ```bash ./scripts/quick-release.sh major ``` ```bash ./scripts/quick-release.sh 1.2.3 ``` -------------------------------- ### Volume instance constants are undefined Source: https://github.com/streamich/memfs/blob/master/docs/node/reference.md Illustrates that constants like `F_OK` are not directly available on a `Volume` instance itself. ```javascript vol.F_OK; // undefined ``` -------------------------------- ### Import Binary Snapshot Synchronously Source: https://github.com/streamich/memfs/blob/master/docs/snapshot/index.md Import a binary snapshot (CBOR Uint8Array) back into a file system synchronously. This restores the file system state from the binary data. ```typescript snapshot.fromBinarySnapshotSync(uint8, { fs, path }); ``` -------------------------------- ### Create File System from JSON with Memfs Source: https://github.com/streamich/memfs/blob/master/docs/node/usage.md Initializes an in-memory file system from a JSON object using `vol.fromJSON`. Files are created relative to the specified directory. ```javascript import { fs, vol } from 'memfs'; const json = { './README.md': '1', './src/index.js': '2', './node_modules/debug/index.js': '3', }; vol.fromJSON(json, '/app'); fs.readFileSync('/app/README.md', 'utf8'); // 1 vol.readFileSync('/app/src/index.js', 'utf8'); // 2 ``` -------------------------------- ### Basic Usage of fs-print Source: https://github.com/streamich/memfs/blob/master/packages/fs-print/README.md Import and use `toTreeSync` to print a file system structure. Requires `memfs` for creating an in-memory file system. ```typescript import { toTreeSync } from '@jsonjoy.com/fs-print'; import { memfs } from 'memfs'; const { fs } = memfs({ '/readme.md': '...', '/src/index.ts': '...', '/src/util.ts': '...', }); console.log(toTreeSync(fs)); ``` -------------------------------- ### Import bound fs functions from fs-like object Source: https://github.com/streamich/memfs/blob/master/docs/node/reference.md Import functions like `createFileSync` and `readFileSync` directly from the `fs`-like object created by `createFsFromVolume`. These methods are bound to the underlying volume. ```javascript const { createFileSync, readFileSync } = fs; ``` -------------------------------- ### Create and Restore Binary (CBOR) Snapshot Synchronously Source: https://github.com/streamich/memfs/blob/master/packages/fs-snapshot/README.md Generate a compact binary snapshot using the synchronous API. This is more efficient for serialization and deserialization. Import `toBinarySnapshotSync` and `fromBinarySnapshotSync`. ```typescript import * as fs from 'fs'; import { toBinarySnapshotSync, fromBinarySnapshotSync } from '@jsonjoy.com/fs-snapshot'; // Create a binary snapshot const binary = toBinarySnapshotSync({ fs, path: '/path/to/directory' }); // Restore from binary snapshot fromBinarySnapshotSync(binary, { fs, path: '/path/to/restore' }); ``` -------------------------------- ### Create and Push Git Tag Source: https://github.com/streamich/memfs/blob/master/scripts/RELEASE.md Stage all changes, commit them with a version message, create a Git tag for the current version, and push the tag and branch to the remote repository. ```bash git add . git commit -m "chore: release v$(node -p "require('./package.json').version")" git tag v$(node -p "require('./package.json').version") git push origin --tags git push origin master ``` -------------------------------- ### Binary Snapshot Operations Source: https://github.com/streamich/memfs/blob/master/docs/snapshot/index.md Create and import binary (CBOR) snapshots of a file system. ```APIDOC ## Binary Snapshot (CBOR) ### Create Binary Snapshot Synchronously ```ts const uint8 = snapshot.toBinarySnapshotSync({ fs, path }); ``` ### Create Binary Snapshot Asynchronously ```ts const uint8 = await snapshot.toBinarySnapshot({ fs: fs.promises, path }); ``` ### Import Binary Snapshot Synchronously ```ts snapshot.fromBinarySnapshotSync(uint8, { fs, path }); ``` ### Import Binary Snapshot Asynchronously ```ts await snapshot.fromBinarySnapshot(uint8, { fs: fs.promises, path }); ``` ``` -------------------------------- ### nodeToFsa(fs, path, opts) Source: https://context7.com/streamich/memfs/llms.txt Wraps any Node.js fs-compatible object (real fs, or a memfs volume) into a FSA FileSystemDirectoryHandle. ```APIDOC ## Adapters ### `nodeToFsa(fs, path, opts)` — wrap any `fs` as a FSA `FileSystemDirectoryHandle` Wraps any Node.js `fs`-compatible object (real `fs`, or a `memfs` volume) into a `FileSystemDirectoryHandle`, making it consumable by browser APIs or libraries that expect the FSA interface. ### Description Adapts a Node.js file system object to be compatible with the browser's File System Access API, enabling its use in environments that expect FSA handles. ### Method `nodeToFsa(fs: object, path: string, opts?: { mode?: 'read' | 'readwrite' | 'readwriteanon' }): FileSystemDirectoryHandle` ### Endpoint N/A (SDK/Library function) ### Parameters - **fs** (`object`) - An object compatible with the Node.js `fs` module (e.g., the real `fs` module or a `memfs` instance). - **path** (`string`) - The root path within the `fs` object to be wrapped. - **opts** (object) - Optional. Configuration for the adapter. - **mode** ('read' | 'readwrite' | 'readwriteanon') - Optional. Specifies the access mode for the filesystem. Defaults to 'readwrite'. ### Request Example ```ts import * as realFs from 'fs'; import { memfs } from 'memfs'; import { nodeToFsa } from 'memfs/lib/node-to-fsa'; // --- Wrap real disk fs --- const diskDir = nodeToFsa(realFs, '/tmp/my-folder', { mode: 'readwrite' }); const file = await diskDir.getFileHandle('test.txt', { create: true }); const w = await file.createWritable(); await w.write('written to real disk via FSA API'); await w.close(); // --- Wrap in-memory memfs --- const { fs } = memfs({ '/project/src/index.ts': 'export {}' }, '/'); const memDir = nodeToFsa(fs, '/project', { mode: 'readwrite' }); // List entries for await (const [name] of memDir.entries()) { console.log(name); // => 'src' } // Create new file through FSA on the in-memory volume const srcDir = await memDir.getDirectoryHandle('src'); const newFile = await srcDir.getFileHandle('app.ts', { create: true }); const ws = await newFile.createWritable(); await ws.write('const app = true;'); await ws.close(); // Verify via original fs fs.readFileSync('/project/src/app.ts', 'utf8'); // => 'const app = true;' ``` ### Response - **FileSystemDirectoryHandle** - A handle representing the root directory of the wrapped filesystem, compatible with the FSA API. ``` -------------------------------- ### Create Resources with FsaCrud Source: https://github.com/streamich/memfs/blob/master/docs/crudfs/index.md Use the `put` method to create or update files within a specified collection. Ensure the collection path and file name are correctly provided. ```javascript await crud.put(['user', 'files'], 'file1.bin', new Uint8Array([1, 2, 3])); await crud.put(['user', 'files'], 'file2.bin', new Uint8Array([1, 2, 3])); ``` -------------------------------- ### Initialize Volume from JSON Source: https://context7.com/streamich/memfs/llms.txt Use `Volume.fromJSON` to create a new in-memory file system from a flat path-to-content map. Multiple independent volumes can be created. Relative paths can be resolved against a base directory when using `new Volume()` and then `fromJSON`. ```typescript import { Volume } from 'memfs'; // Construct from flat JSON (keys are absolute paths) const vol = Volume.fromJSON({ '/etc/hosts': '127.0.0.1 localhost', '/etc/resolv.conf': 'nameserver 8.8.8.8', '/home/user/.bashrc': 'export PATH=$PATH:/usr/local/bin', }); vol.readFileSync('/etc/hosts', 'utf8'); // => '127.0.0.1 localhost' // Multiple independent volumes const vol2 = Volume.fromJSON({ '/tmp/data.txt': 'volume 2' }); vol2.readFileSync('/tmp/data.txt', 'utf8'); // => 'volume 2' vol.existsSync('/tmp/data.txt'); // => false // fromJSON with a base directory (relative keys resolved against it) const vol3 = new Volume(); vol3.fromJSON( { './index.js': 'export default 42', './package.json': '{"type":"module"}', }, '/project', ); vol3.readFileSync('/project/index.js', 'utf8'); // => 'export default 42' ``` -------------------------------- ### Create and Restore Synchronous Snapshot Source: https://github.com/streamich/memfs/blob/master/packages/fs-snapshot/README.md Use the synchronous API to create a file system snapshot and restore it to a different location. Ensure you have the `fs` module imported. ```typescript import * as fs from 'fs'; import { toSnapshotSync, fromSnapshotSync } from '@jsonjoy.com/fs-snapshot'; // Create a snapshot of a directory const snapshot = toSnapshotSync({ fs, path: '/path/to/directory' }); // Restore the snapshot to a different location fromSnapshotSync(snapshot, { fs, path: '/path/to/restore' }); ``` -------------------------------- ### toTreeSync(fs, opts) Source: https://context7.com/streamich/memfs/llms.txt Renders any fs-like file system or a subdirectory as an ASCII tree string. Supports depth limiting, sorting, and custom root paths. ```APIDOC ## toTreeSync(fs, opts) ### Description Renders any `fs`-like file system (or a subdirectory of it) as an ASCII tree string. Supports depth limiting, alphabetical sorting (folders first by default), and custom root paths. ### Parameters #### Path Parameters - **fs** (object) - Required - An fs-like file system object. - **opts** (object) - Optional - Options for rendering the tree. - **dir** (string) - The root directory to start rendering from. - **depth** (number) - The maximum depth to render. - **sort** (boolean) - Whether to sort the entries alphabetically (folders first by default). ### Request Example ```typescript import * as fs from 'fs'; import { memfs } from 'memfs'; import { toTreeSync } from 'memfs/lib/print'; // With real fs console.log(toTreeSync(fs, { dir: process.cwd() + '/src' })); // With in-memory fs const { fs: memFs } = memfs({ '/app/package.json': '', '/app/src/index.ts': '', '/app/src/components/Button.tsx': '', '/app/src/components/Input.tsx': '', '/app/tests/index.test.ts': '', }, '/'); console.log(toTreeSync(memFs, { dir: '/app' })); console.log(toTreeSync(memFs, { dir: '/app', depth: 1 })); console.log(toTreeSync(memFs, { dir: '/app/src/components', sort: false })); ``` ### Response #### Success Response (string) - Returns an ASCII string representing the directory tree. ``` -------------------------------- ### Write File using FsaNodeFs Promises API Source: https://github.com/streamich/memfs/blob/master/docs/fsa/fsa-to-fs.md Demonstrates writing to a file using the promises API of the FsaNodeFs instance. ```javascript await fs.promises.writeFile('/hello.txt', 'Hello World!'); ``` -------------------------------- ### Typecheck All Packages Source: https://github.com/streamich/memfs/blob/master/CONTRIBUTING.md Run this command to perform type checking across all packages. ```bash yarn typecheck ``` -------------------------------- ### Create Current Working Directory in Memfs Source: https://github.com/streamich/memfs/blob/master/docs/node/relative-paths.md Use `mkdirSync` with `recursive: true` to create the current working directory within the memfs volume, enabling relative path resolution. ```javascript vol.mkdirSync(process.cwd(), { recursive: true }); ``` -------------------------------- ### Snapshot Utilities Source: https://context7.com/streamich/memfs/llms.txt Serializes and restores file system trees to various formats (POJO, CBOR, JSON Uint8Array). Supports files, directories, and symlinks. ```APIDOC ## `snapshot` — serialize and restore file system trees ### Description The `snapshot` module serializes any `fs`-like directory (including real `fs`, `memfs`, or `FsaNodeFs`) to POJO, binary CBOR, or JSON `Uint8Array` formats, and restores them later. Supports files, directories, and symlinks. ### POJO Snapshot (Synchronous) ```ts import * as snapshot from 'memfs/lib/snapshot'; import { memfs } from 'memfs'; const { fs: sourceFs } = memfs({ '/project/README.md': '# Hello', '/project/src/index.ts': 'export const x = 1;', '/project/empty': null, }, '/'); const pojoSnap = snapshot.toSnapshotSync({ fs: sourceFs, path: '/project' }); const { fs: targetFs, vol: targetVol } = memfs(); snapshot.fromSnapshotSync(pojoSnap, { fs: targetFs, path: '/restored' }); targetVol.toJSON(); // => { '/restored/README.md': '# Hello', '/restored/src/index.ts': 'export const x = 1;', '/restored/empty': null } ``` ### POJO Snapshot (Asynchronous) ```ts import * as snapshot from 'memfs/lib/snapshot'; const asyncSnap = await snapshot.toSnapshot({ fs: sourceFs.promises, path: '/project' }); await snapshot.fromSnapshot(asyncSnap, { fs: targetFs.promises, path: '/async-restored' }); ``` ### Binary CBOR Snapshot (Compact, Supports Binary Data) ```ts import * as snapshot from 'memfs/lib/snapshot'; const bin: Uint8Array = snapshot.toBinarySnapshotSync({ fs: sourceFs, path: '/project' }); console.log(bin instanceof Uint8Array); // => true const { fs: binTarget } = memfs(); snapshot.fromBinarySnapshotSync(bin, { fs: binTarget, path: '/from-bin' }); binTarget.readFileSync('/from-bin/README.md', 'utf8'); // => '# Hello' ``` ### JSON Uint8Array Snapshot (Base64-encodes Binary Files) ```ts import * as snapshot from 'memfs/lib/snapshot'; const jsonBin: Uint8Array = snapshot.toJsonSnapshotSync({ fs: sourceFs, path: '/project' }); const { fs: jsonTarget } = memfs(); snapshot.fromJsonSnapshotSync(jsonBin, { fs: jsonTarget, path: '/from-json' }); jsonTarget.readFileSync('/from-json/src/index.ts', 'utf8'); // => 'export const x = 1;' ``` ``` -------------------------------- ### Binary (CBOR) Snapshots Source: https://github.com/streamich/memfs/blob/master/packages/fs-snapshot/README.md APIs for creating and restoring file system snapshots in a compact binary (CBOR) format. ```APIDOC ## toBinarySnapshotSync ### Description Creates a synchronous binary (CBOR) snapshot of a directory. ### Signature `toBinarySnapshotSync({ fs, path: string }): Uint8Array` ### Parameters - **fs** (`object`) - The Node.js `fs` module. - **path** (`string`) - The path to the directory to snapshot. ### Request Example ```ts import * as fs from 'fs'; import { toBinarySnapshotSync } from '@jsonjoy.com/fs-snapshot'; const binary = toBinarySnapshotSync({ fs, path: '/path/to/directory' }); ``` ## fromBinarySnapshotSync ### Description Restores a file system snapshot from binary (CBOR) format synchronously. ### Signature `fromBinarySnapshotSync(binary: Uint8Array, { fs, path: string }): void` ### Parameters - **binary** (`Uint8Array`) - The binary snapshot data to restore. - **fs** (`object`) - The Node.js `fs` module. - **path** (`string`) - The path where the snapshot should be restored. ### Request Example ```ts import * as fs from 'fs'; import { fromBinarySnapshotSync } from '@jsonjoy.com/fs-snapshot'; fromBinarySnapshotSync(binary, { fs, path: '/path/to/restore' }); ``` ``` -------------------------------- ### Check Formatting Source: https://github.com/streamich/memfs/blob/master/CONTRIBUTING.md Use this command to check code formatting in all packages against Prettier rules. ```bash yarn prettier:check ``` -------------------------------- ### CRUD File System Abstraction with `FsaCrud` and `NodeCrud` Source: https://context7.com/streamich/memfs/llms.txt Provides a simple `put/get/delete/list/drop` API over file systems, treating directories as collections and files as resources. Useful for key-value-like storage. ```typescript import { memfs } from 'memfs'; import { nodeToFsa } from 'memfs/lib/node-to-fsa'; import { FsaCrud } from 'memfs/lib/fsa-to-crud'; import { NodeCrud } from 'memfs/lib/node-to-crud'; // --- FsaCrud on top of in-memory memfs --- const { fs } = memfs({}, '/'); const dir = nodeToFsa(fs, '/', { mode: 'readwrite' }); const crud = new FsaCrud(dir); // Put resources await crud.put(['users', 'profiles'], 'alice.json', new TextEncoder().encode('{"name":"Alice"}')); await crud.put(['users', 'profiles'], 'bob.json', new TextEncoder().encode('{"name":"Bob"}')); // List collection const items = await crud.list(['users', 'profiles']); console.log(items.map(i => i.id)); // => ['alice.json', 'bob.json'] // Get a resource const raw = await crud.get(['users', 'profiles'], 'alice.json'); console.log(new TextDecoder().decode(raw)); // => '{"name":"Alice"}' // Delete a resource await crud.del(['users', 'profiles'], 'bob.json'); // Drop the entire collection await crud.drop(['users', 'profiles']); // --- NodeCrud directly on Node.js fs --- import * as realFs from 'fs'; const nodeCrud = new NodeCrud({ fs: realFs.promises, dir: '/tmp/crud-store' }); await nodeCrud.put(['logs'], 'app.log', new TextEncoder().encode('started')); const log = await nodeCrud.get(['logs'], 'app.log'); console.log(new TextDecoder().decode(log)); // => 'started' ``` -------------------------------- ### Import POJO Snapshot Synchronously Source: https://github.com/streamich/memfs/blob/master/docs/snapshot/index.md Import a POJO snapshot back into a file system synchronously. Ensure the snapshot object is valid and the target path is accessible. ```typescript snapshot.fromSnapshotSync(snap, { fs, path }); ``` -------------------------------- ### Initialize FsaCrud with File System Access API Source: https://github.com/streamich/memfs/blob/master/docs/crudfs/index.md Construct a crudfs instance using the File System Access API's FileSystemDirectoryHandle. This allows direct CRUD operations on the file system. ```javascript import { FsaCrud } from 'memfs/lib/fsa-to-crud'; const crud = new FsaCrud(dirHandle); ```