In current Node.js, specifiers starting with https:// are unsupported. 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.mjsimport { get } from 'https';export function resolve(specifier, context, defaultResolve) {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 {url: specifier};} else if (parentURL && parentURL.startsWith('https://')) {return {url: new URL(specifier, parentURL).href};}// Let Node.js handle all other specifiers.return defaultResolve(specifier, context, defaultResolve);}export function getFormat(url, context, defaultGetFormat) {// This loader assumes all network-provided JavaScript is ES module code.if (url.startsWith('https://')) {return {format: 'module'};}// Let Node.js handle all other URLs.return defaultGetFormat(url, context, defaultGetFormat);}export function getSource(url, context, defaultGetSource) {// 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({ source: data }));}).on('error', (err) => reject(err));});}// Let Node.js handle all other URLs.return defaultGetSource(url, context, defaultGetSource);}
// main.mjsimport { VERSION } from 'https://coffeescript.org/browser-compiler-modern/coffeescript.js';console.log(VERSION);
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.
