node:module exports createRequire, isBuiltin, builtinModules, and the rest of
Node’s module helpers.
Example
// module.mjs
import { builtinModules, createRequire, isBuiltin } from "node:module";
const require = createRequire(import.meta.url);
const { basename } = require("node:path");
console.log(basename("/srv/app/main.js"));
console.log(isBuiltin("node:fs"), isBuiltin("fs/promises"), isBuiltin("left-pad"));
console.log(builtinModules.includes("worker_threads"));
elide run module.mjs prints:
main.js
true true false
true
Loader hooks
registerHooks({ resolve, load }) adds synchronous hooks to require and import. Hooks chain with the
last registered running first; each calls next to continue or returns shortCircuit: true.
deregister() removes them.
// greeting.mjs
export default "hello";
// hooks.mjs
import { registerHooks } from "node:module";
const hooks = registerHooks({
resolve(specifier, context, next) {
if (specifier === "virtual:greeting") {
return { url: new URL("./greeting.mjs", import.meta.url).href, shortCircuit: true };
}
return next(specifier, context);
},
load(url, context, next) {
const result = next(url, context);
if (url.endsWith("/greeting.mjs")) {
return { format: "module", source: String(result.source).replace("hello", "hooked") };
}
return result;
},
});
const { default: greeting } = await import("virtual:greeting");
console.log(greeting);
hooks.deregister();
elide run hooks.mjs prints hooked.
Differences from Node
createRequirereturns the realm’srequire; relative paths do not resolve against the filename passed to it.syncBuiltinESMExports()is a no-op.findSourceMap()returnsundefined;getSourceMapsSupport()reports source maps disabled.- Asynchronous loader hooks (
register) are not supported; useregisterHooks. require.resolve()returns the specifier unchanged for built-ins.
Reference
Status: Partial · 45 of 52 suite tests pass (86.5%)
module exports
Module, builtinModules, createRequire, findSourceMap, getSourceMapsSupport, globalPaths, isBuiltin, registerHooks, runMain, setSourceMapsSupport, syncBuiltinESMExports, wrap, wrapper
Not implemented
SourceMap, constants, enableCompileCache, findPackageJSON, flushCompileCache, getCompileCacheDir, register, stripTypeScriptTypes.
Tests: node-api node:module-loading: 45 pass, 7 fail, 0 error, 5 skipped. Failing: test-module-loading-globalpaths.js, test-module-main-fail.js, test-module-main-preserve-symlinks-fail.js, test-module-prototype-mutation.js, test-module-run-main-monkey-patch.js, test-require-package-map.js, test-require-symlink.js.