资源的虚拟文件系统(VFS)


🌐 Virtual file system (VFS) for assets

稳定性: 1.0 - 早期开发

除了使用 node:sea API 访问单个资源外,打包的资源还可以作为只读的 虚拟文件系统 暴露,并通过标准的 node:fs API 进行访问。要启用此功能,请在 SEA 配置中设置 "useVfs": true。

🌐 In addition to using the node:sea API to access individual assets, the bundled assets can be exposed as a read-only virtual file system and accessed through standard node:fs APIs. To enable this, set "useVfs": true in the SEA configuration.

虚拟文件系统从不覆盖真实文件系统:它挂载在一个真实文件系统中不存在的保留挂载点上,挂载点是在运行时选择的,而不是固定路径。当启用 useVfs 时,注入的主脚本本身会放在挂载根目录并从那里执行,所以 __filename 和 __dirname 指向虚拟文件系统内部,而不是反映 process.execPath。因此,打包的代码可以通过 __dirname 相对路径和相对 require() 调用来访问资源,而无需知道挂载点:

🌐 A virtual file system never shadows the real file system: it is mounted at a reserved mount point that cannot exist on the real file system, and the mount point is chosen at runtime rather than being a fixed path. When useVfs is enabled, the injected main script itself is placed at the root of the mount and executed from there, so __filename and __dirname point inside the virtual file system instead of reflecting process.execPath. Bundled code therefore reaches the assets through __dirname-relative paths and relative require() calls, without having to know the mount point:

const fs = require('node:fs');
const path = require('node:path');

// __dirname is the root of the virtual file system holding the assets.
const rawConfig = fs.readFileSync(path.join(__dirname, 'config.json'), 'utf8');
const data = fs.readFileSync(path.join(__dirname, 'data/file.txt'));

// Directory operations work too.
const files = fs.readdirSync(path.join(__dirname, 'assets'));

// Check if a bundled file exists.
if (fs.existsSync(path.join(__dirname, 'optional.json'))) {
  // ...
} 

VFS 支持 node:fs 操作用于读取文件和目录。由于 SEA VFS 是只读的,写操作会因 EROFS 而失败。查看 VFS 文档 获取完整的支持操作列表。

🌐 The VFS supports the node:fs operations for reading files and directories. Since the SEA VFS is read-only, write operations fail with EROFS. See the VFS documentation for the full list of supported operations.