Skip to content

Commit 7258d38

Browse files
committed
add some properties to require
1 parent 2ece9a5 commit 7258d38

File tree

1 file changed

+13
-2
lines changed

1 file changed

+13
-2
lines changed

lib/internal/modules/esm/translators.js

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ const { fileURLToPath, pathToFileURL, URL } = require('internal/url');
4141
let debug = require('internal/util/debuglog').debuglog('esm', (fn) => {
4242
debug = fn;
4343
});
44-
const { emitExperimentalWarning, kEmptyObject } = require('internal/util');
44+
const { emitExperimentalWarning, kEmptyObject, setOwnProperty } = require('internal/util');
4545
const {
4646
ERR_UNKNOWN_BUILTIN_MODULE,
4747
ERR_INVALID_RETURN_PROPERTY_VALUE,
@@ -147,7 +147,7 @@ const cjsCache = new SafeMap();
147147
function createCJSModuleWrap(url, source) {
148148
debug(`Translating CJSModule ${url}`);
149149

150-
const filename = fileURLToPath(new URL(url));
150+
const filename = StringPrototypeStartsWith(url, 'file://') ? fileURLToPath(url) : url;
151151

152152
const { exportNames, module } = cjsPreparseModuleExports(filename, source);
153153
const namesWithDefault = exportNames.has('default') ?
@@ -173,6 +173,16 @@ function createCJSModuleWrap(url, source) {
173173
job.runSync();
174174
return cjsCache.get(job.url).exports;
175175
};
176+
setOwnProperty(require, 'resolve', function resolve(spec) {
177+
// TODO: add support for absolute paths
178+
if (spec[0] === '.') {
179+
spec = pathToFileURL(join(__dirname, spec));
180+
}
181+
const { url: resolvedURL } = asyncESM.esmLoader.resolve(spec, url);
182+
return StringPrototypeStartsWith(resolvedURL, 'file://') ? fileURLToPath(resolvedURL) : resolvedURL;
183+
});
184+
setOwnProperty(require, 'cache', CJSModule._cache);
185+
setOwnProperty(require, 'main', process.mainModule);
176186

177187
cjsCache.set(url, module);
178188
ReflectApply(compiledWrapper, module.exports,
@@ -211,6 +221,7 @@ translators.set('commonjs', async function commonjsStrategy(url, source,
211221
});
212222

213223
function cjsPreparseModuleExports(filename, source) {
224+
// TODO: Do we want to keep hitting the user mutable CJS loader here?
214225
let module = CJSModule._cache[filename];
215226
if (module) {
216227
const cached = cjsParseCache.get(module);

0 commit comments

Comments
 (0)