HTTPS 加载器


¥HTTPS loader

在当前的 Node.js 中,以 https:// 开头的说明符是实验性的(请参阅 HTTPS 和 HTTP 导入)。

¥In current Node.js, specifiers starting with https:// are experimental (see HTTPS and HTTP imports).

下面的加载器注册钩子以启用对此类说明符的基本支持。虽然这看起来像是对 Node.js 核心功能的重大改进,但实际使用此加载器有很大的缺点:性能比从磁盘加载文件慢得多,没有缓存,也没有安全性。

¥The loader below registers hooks to enable rudimentary support for such specifiers. While this may seem like a significant improvement to Node.js core functionality, there are substantial downsides to actually using this loader: performance is much slower than loading files from disk, there is no caching, and there is no security.

// https-loader.mjs
import { get } from 'node:https';

export function resolve(specifier, context, nextResolve) {
  const { parentURL = null } = context;

  // Normally Node.js would error on specifiers starting with 'https://', so
  // this hook intercepts them and converts them into absolute URLs to be
  // passed along to the later hooks below.
  if (specifier.startsWith('https://')) {
    return {
      shortCircuit: true,
      url: specifier
    };
  } else if (parentURL && parentURL.startsWith('https://')) {
    return {
      shortCircuit: true,
      url: new URL(specifier, parentURL).href,
    };
  }

  // Let Node.js handle all other specifiers.
  return nextResolve(specifier);
}

export function load(url, context, nextLoad) {
  // For JavaScript to be loaded over the network, we need to fetch and
  // return it.
  if (url.startsWith('https://')) {
    return new Promise((resolve, reject) => {
      get(url, (res) => {
        let data = '';
        res.on('data', (chunk) => data += chunk);
        res.on('end', () => resolve({
          // This example assumes all network-provided JavaScript is ES module
          // code.
          format: 'module',
          shortCircuit: true,
          source: data,
        }));
      }).on('error', (err) => reject(err));
    });
  }

  // Let Node.js handle all other URLs.
  return nextLoad(url);
} 
// main.mjs
import { VERSION } from 'https://coffeescript.org/browser-compiler-modern/coffeescript.js';

console.log(VERSION); 

使用前面的加载器,运行 node --experimental-loader ./https-loader.mjs ./main.mjs 会在 main.mjs 中的 URL 处按照模块打印当前版本的 CoffeeScript。

¥With the preceding loader, running node --experimental-loader ./https-loader.mjs ./main.mjs prints the current version of CoffeeScript per the module at the URL in main.mjs.