diff --git a/doc/api/vfs.md b/doc/api/vfs.md index 87b37819c0fe48..24df60bbb9723a 100644 --- a/doc/api/vfs.md +++ b/doc/api/vfs.md @@ -46,6 +46,11 @@ callback-based, and promise-based file system methods that mirror the shape of the [`node:fs`][] API. All paths are POSIX-style and absolute (starting with `/`). +By default, the file tree is private to the VFS instance. To expose +it through the global `node:fs` module, `require()`, and `import`, +call [`vfs.mount(prefix)`][]; call [`vfs.unmount()`][] (or rely on a +`using` declaration) to detach again. + ## `vfs.create([provider][, options])` + +* `prefix` {string} The path prefix where the VFS will be mounted. +* Returns: {VirtualFileSystem} The VFS instance, for chaining or `using`. + +Mounts the virtual file system at the specified path prefix. After +mounting, files in the VFS can be accessed through the `node:fs` +module — and resolved through `require()` and `import` — using paths +that start with the prefix. + +If a real file-system path already exists at the mount prefix, the +VFS **shadows** that path: every operation against a path under the +mount point is directed to the VFS until the VFS is unmounted. + +```cjs +const vfs = require('node:vfs'); +const fs = require('node:fs'); + +const myVfs = vfs.create(); +myVfs.writeFileSync('/data.txt', 'Hello'); +myVfs.mount('/virtual'); + +fs.readFileSync('/virtual/data.txt', 'utf8'); // 'Hello' +``` + +Each `VirtualFileSystem` instance may be mounted at most once at a +time. Attempting to mount an already-mounted instance throws +`ERR_INVALID_STATE`. Mounting two instances at overlapping prefixes +(e.g., `/virtual` and `/virtual/sub`) also throws `ERR_INVALID_STATE`. + +The VFS supports the [Explicit Resource Management][] proposal. Use +a `using` declaration to unmount automatically when leaving scope: + +```cjs +const vfs = require('node:vfs'); +const fs = require('node:fs'); + +{ + using myVfs = vfs.create(); + myVfs.writeFileSync('/data.txt', 'Hello'); + myVfs.mount('/virtual'); + + fs.readFileSync('/virtual/data.txt', 'utf8'); // 'Hello' +} // VFS is automatically unmounted here + +fs.existsSync('/virtual/data.txt'); // false +``` + +### `vfs.unmount()` + + + +Unmounts the virtual file system. After unmounting, virtual files +are no longer reachable through `node:fs`, `require()`, or `import`. +The same instance may be mounted again, at the same or a different +prefix, by calling `mount()`. + +This method is idempotent: calling `unmount()` on a VFS that is not +currently mounted has no effect. + +### `vfs.mounted` + + + +* {boolean} + +`true` while the VFS is mounted; `false` otherwise. + +### `vfs.mountPoint` + + + +* {string | null} + +The current mount-point path as an absolute string, or `null` when +the VFS is not mounted. + ### `vfs.provider`