从 HTTPS 导入


\Import from HTTPS

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

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

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

\The hook 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 these hooks: performance is much slower than loading files from disk, there is no caching, and there is no security.

// https-hooks.mjs
import { get } from 'node:https';
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.setEncoding('utf8');
 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); 

使用前面的 hooks 模块,运行 node --import 'data:text/javascript,import { register } from "node:module"; import { pathToFileURL } from "node:url"; register(pathToFileURL("./https-hooks.mjs"));' ./main.mjs 会在 main.mjs 中的 URL 处打印每个模块的 CoffeeScript 的当前版本。

\With the preceding hooks module, running node --import 'data:text/javascript,import { register } from "node:module"; import { pathToFileURL } from "node:url"; register(pathToFileURL("./https-hooks.mjs"));' ./main.mjs prints the current version of CoffeeScript per the module at the URL in main.mjs.

AltStyle によって変換されたページ (->オリジナル) /