vfs.mount()
- 返回:<string> 绝对挂载点
挂载虚拟文件系统并返回生成的挂载点。挂载后,可以通过 node:fs 模块访问 VFS 中的文件,并通过 require() 和 import 使用返回挂载点下的路径进行解析。
🌐 Mounts the virtual file system and returns the resulting mount point.
After mounting, files in the VFS can be accessed through the
node:fs module and resolved through require() and import
using paths under the returned mount point.
挂载点总是存在于一个保留的命名空间中,该命名空间不能有子文件系统条目,因此虚拟路径永远不会与真实路径混淆或重叠。挂载点是从 vfs.mount() 返回的内容或从 vfs.mountPoint 获取的,所有已挂载文件系统的挂载点可以通过读取 保留根目录 来列出,其路径由 vfs.vfsBase() 返回。该目录中挂载点的名称是在运行时分配的,所以不应该去构造或硬编码它。
🌐 Mount points always live inside a reserved namespace that cannot have child file system entries,
so virtual paths never conflate with (or shadow) real paths. A mount point is obtained from what
vfs.mount() returns or from vfs.mountPoint, and the mount points of all mounted file
systems can be listed by reading the reserved root directory, whose path vfs.vfsBase()
returns. The name of a mount point within that directory is assigned at runtime, so it is not
something to construct or hard-code.
const vfs = require('node:vfs');
const fs = require('node:fs');
const myVfs = vfs.create();
myVfs.writeFileSync('/data.txt', 'Hello');
const mountPoint = myVfs.mount();
// e.g. '/dev/null/vfs/0'
fs.readFileSync(`${mountPoint}/data.txt`, 'utf8'); // 'Hello' 像任何挂载点一样,挂载点不能被移除或重命名,也不能通过将其他东西重命名到它上面来替换:fs.rmdir() 和 fs.rename() 会因 EBUSY 失败。对挂载点进行递归 fs.rm() 会在以相同方式失败之前清空文件系统。
🌐 Like any mount point, the mount point cannot be removed or renamed, nor
replaced by renaming something else onto it: fs.rmdir() and
fs.rename() fail with EBUSY. A recursive fs.rm() of the mount
point empties the file system before failing the same way.
每个 VirtualFileSystem 实例最多只能同时挂载一次。尝试挂载已挂载的实例会抛出 ERR_INVALID_STATE。由于每个实例都挂载在自己独立的每层命名空间中,不同实例的挂载永远不会重叠。
🌐 Each VirtualFileSystem instance may be mounted at most once at a
time. Attempting to mount an already-mounted instance throws
ERR_INVALID_STATE. Because each instance mounts inside its own
per-layer namespace, mounts from different instances can never
overlap.
VFS 支持 显式资源管理 提案。使用 using 声明,在离开作用域时自动卸载:
🌐 The VFS supports the Explicit Resource Management proposal. Use
a using declaration to unmount automatically when leaving scope:
const vfs = require('node:vfs');
const fs = require('node:fs');
let mountPoint;
{
using myVfs = vfs.create();
myVfs.writeFileSync('/data.txt', 'Hello');
mountPoint = myVfs.mount();
fs.readFileSync(`${mountPoint}/data.txt`, 'utf8'); // 'Hello'
} // VFS is automatically unmounted here
fs.existsSync(`${mountPoint}/data.txt`); // false