Skip to content

Commit

Permalink
esm: skip file: URL conversion to path when possible
Browse files Browse the repository at this point in the history
  • Loading branch information
aduh95 committed Jan 19, 2023
1 parent 00cd18f commit 1fc0fb0
Showing 1 changed file with 27 additions and 3 deletions.
30 changes: 27 additions & 3 deletions lib/internal/modules/esm/get_format.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@ const {
ObjectPrototypeHasOwnProperty,
PromisePrototypeThen,
PromiseResolve,
StringPrototypeCharCodeAt,
StringPrototypeSlice,
} = primordials;
const { basename, extname, relative } = require('path');
const { basename, relative } = require('path');
const { getOptionValue } = require('internal/options');
const {
extensionFormatMap,
Expand Down Expand Up @@ -41,15 +42,37 @@ function getDataProtocolModuleFormat(parsed) {
return mimeToFormat(mime);
}

const DOT_CODE = 46;
const SLASH_CODE = 47;

/**
* Returns the file extension from a file: URL. Should give similar result than
* require('node:path').extname(require('node:url').fileURLToPath(url)).
* @param {URL} url A file: URL.
* @returns {string}
*/
function extname(url) {
const { pathname } = url;
for (let i = pathname.length - 1; i > 0; i--) {
switch (StringPrototypeCharCodeAt(pathname, i)) {
case SLASH_CODE:
return '';

case DOT_CODE:
return StringPrototypeSlice(pathname, i);
}
}
return '';
}

/**
* @param {URL} url
* @param {{parentURL: string}} context
* @param {boolean} ignoreErrors
* @returns {string}
*/
function getFileProtocolModuleFormat(url, context, ignoreErrors) {
const filepath = fileURLToPath(url);
const ext = extname(filepath);
const ext = extname(url);
if (ext === '.js') {
return getPackageType(url) === 'module' ? 'module' : 'commonjs';
}
Expand All @@ -59,6 +82,7 @@ function getFileProtocolModuleFormat(url, context, ignoreErrors) {

// Explicit undefined return indicates load hook should rerun format check
if (ignoreErrors) { return undefined; }
const filepath = fileURLToPath(url);
let suggestion = '';
if (getPackageType(url) === 'module' && ext === '') {
const config = getPackageScopeConfig(url);
Expand Down

0 comments on commit 1fc0fb0

Please sign in to comment.