从 HTTPS 导入
下面的钩子注册了一些钩子,以对此类说明符提供基本的 支持。虽然这看起来像是 Node.js 核心 功能的一大改进,但实际使用这些钩子有诸多弊端: 性能比从磁盘加载文件慢得多,没有缓存, 也没有安全性。
// https-hooks.mjs
import { get } from 'node:https';
export function load(url, context, nextLoad) {
// 要通过加载网络上的 JavaScript,我们需要获取并
// 返回它。
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({
// 此示例假定所有网络提供的 JavaScript 都是 ES 模块
// 代码。
format: 'module',
shortCircuit: true,
source: data,
}));
}).on('error', (err) => reject(err));
});
}
// 让 Node.js 处理所有其他 URL。
return nextLoad(url);
} // main.mjs
import { VERSION } from 'https://coffeescript.org/browser-compiler-modern/coffeescript.js';
console.log(VERSION); 使用上述钩子模块,运行
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 的
当前版本。