Skip to content

Commit 1fc0fb0

Browse files
committed
esm: skip file: URL conversion to path when possible
1 parent 00cd18f commit 1fc0fb0

File tree

1 file changed

+27
-3
lines changed

1 file changed

+27
-3
lines changed

lib/internal/modules/esm/get_format.js

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,10 @@ const {
44
ObjectPrototypeHasOwnProperty,
55
PromisePrototypeThen,
66
PromiseResolve,
7+
StringPrototypeCharCodeAt,
78
StringPrototypeSlice,
89
} = primordials;
9-
const { basename, extname, relative } = require('path');
10+
const { basename, relative } = require('path');
1011
const { getOptionValue } = require('internal/options');
1112
const {
1213
extensionFormatMap,
@@ -41,15 +42,37 @@ function getDataProtocolModuleFormat(parsed) {
4142
return mimeToFormat(mime);
4243
}
4344

45+
const DOT_CODE = 46;
46+
const SLASH_CODE = 47;
47+
48+
/**
49+
* Returns the file extension from a file: URL. Should give similar result than
50+
* require('node:path').extname(require('node:url').fileURLToPath(url)).
51+
* @param {URL} url A file: URL.
52+
* @returns {string}
53+
*/
54+
function extname(url) {
55+
const { pathname } = url;
56+
for (let i = pathname.length - 1; i > 0; i--) {
57+
switch (StringPrototypeCharCodeAt(pathname, i)) {
58+
case SLASH_CODE:
59+
return '';
60+
61+
case DOT_CODE:
62+
return StringPrototypeSlice(pathname, i);
63+
}
64+
}
65+
return '';
66+
}
67+
4468
/**
4569
* @param {URL} url
4670
* @param {{parentURL: string}} context
4771
* @param {boolean} ignoreErrors
4872
* @returns {string}
4973
*/
5074
function getFileProtocolModuleFormat(url, context, ignoreErrors) {
51-
const filepath = fileURLToPath(url);
52-
const ext = extname(filepath);
75+
const ext = extname(url);
5376
if (ext === '.js') {
5477
return getPackageType(url) === 'module' ? 'module' : 'commonjs';
5578
}
@@ -59,6 +82,7 @@ function getFileProtocolModuleFormat(url, context, ignoreErrors) {
5982

6083
// Explicit undefined return indicates load hook should rerun format check
6184
if (ignoreErrors) { return undefined; }
85+
const filepath = fileURLToPath(url);
6286
let suggestion = '';
6387
if (getPackageType(url) === 'module' && ext === '') {
6488
const config = getPackageScopeConfig(url);

0 commit comments

Comments
 (0)