vfs.registerProvider(entry)


  • entry <Object>
    • name <string> 一个简短的标识符,用于诊断。
    • canHandle <Function> 用解析后的路径和它的 fs.Stats 调用。如果这个提供者应该支持该来源,则返回 true。
    • create <Function> 使用解析后的路径及其 fs.Stats 调用。返回支持源的 VirtualProvider。

注册一个提供者,让 --vfs-load 可以为它识别的源选择,这样 Node.js 没有内置提供者的文件格式仍然可以被挂载。

🌐 Registers a provider that --vfs-load can select for a source it recognizes, so a file format Node.js has no built-in provider for can still be mounted.

一个源会被第一个返回 true 的 canHandle() 的提供者认领。注册提供者会在内置提供者之前被咨询,最新注册的优先,并且它们既可以提供目录也可以提供文件,所以注册提供者可以备份、封装或审核任何源。如果没有提供者认领该源,内置提供者会处理它:一个带有 RealFSProvider 的目录,以及一个字节是包含 ZipProvider 的 ZIP 压缩文件的文件。

🌐 A source is claimed by the first provider whose canHandle() returns true. Registered providers are consulted before the built-in ones, newest registration first, and are offered directories as well as files, so a registered provider can back, wrap, or vet any source. If none claims the source, the built-in providers handle it: a directory with RealFSProvider, and a file whose bytes are a ZIP archive with ZipProvider.

在挂载源之前,提供者必须先注册。可以从预先加载了 --require 或 --import 的模块进行注册:

🌐 Providers must be registered before the source is mounted. Register from a module preloaded with --require or --import:

// provider.js, preloaded with --require
const fs = require('node:fs');
const vfs = require('node:vfs');

const MAGIC = Buffer.from('CUSTOMFMT');

vfs.registerProvider({
  name: 'customfmt',
  canHandle(path, stats) {
    if (!stats.isFile()) return false;
    const head = Buffer.alloc(MAGIC.length);
    const fd = fs.openSync(path, 'r');
    try {
      fs.readSync(fd, head, 0, MAGIC.length, 0);
    } finally {
      fs.closeSync(fd);
    }
    return head.equals(MAGIC);
  },
  create(path) {
    return new MyCustomProvider(path);
  },
}); 
$ node --experimental-vfs --require ./provider.js \
       --vfs-load archive.customfmt