On this page

The Module object

History
Type:Object

Provides general utility methods when interacting with instances of Module, the module variable often seen in CommonJS modules. Accessed via import 'node:module' or require('node:module').

P

module.builtinModules

History
Type:string[]

A list of the names of all modules provided by Node.js. Can be used to verify if a module is maintained by a third party or not.

module in this context isn't the same object that's provided by the module wrapper. To access it, require the Module module:

// module.mjs
// In an ECMAScript module
import { builtinModules as builtin } from 'node:module';
// module.cjs
// In a CommonJS module
const builtin = require('node:module').builtinModules;
M

module.createRequire

History
module.createRequire(filename): require
Attributes
filename:string | URL
Filename to be used to construct the require function. Must be a file URL object, file URL string, or absolute path string.
Returns:require
Require function
import { createRequire } from 'node:module';
const require = createRequire(import.meta.url);

// sibling-module.js is a CommonJS module.
const siblingModule = require('./sibling-module');
M

module.findPackageJSON

History
module.findPackageJSON(specifier, base?): string | undefined
Stability: 1.1Active Development
Attributes
specifier:string | URL
The specifier for the module whose package.json to retrieve. When passing a bare specifier, the package.json at the root of the package is returned. When passing a relative specifier or an absolute specifier, the closest parent package.json is returned.
base:string | URL
The absolute location (file: URL string or FS path) of the containing module. For CJS, use __filename (not __dirname!); for ESM, use import.meta.url. You do not need to pass it if specifier is an absolute specifier.
Returns:string | undefined
A path if the package.json is found. When specifier is a package, the package's root package.json; when a relative or unresolved, the closest package.json to the specifier.

Caveat: Do not use this to try to determine module format. There are many things affecting that determination; the type field of package.json is the least definitive (ex file extension supersedes it, and a loader hook supersedes that).

Caveat: This currently leverages only the built-in default resolver; if resolve customization hooks are registered, they will not affect the resolution. This may change in the future.

/path/to/project
  ├ packages/
    ├ bar/
      ├ bar.js
      └ package.json // name = '@foo/bar'
    └ qux/
      ├ node_modules/
        └ some-package/
          └ package.json // name = 'some-package'
      ├ qux.js
      └ package.json // name = '@foo/qux'
  ├ main.js
  └ package.json // name = '@foo'
// /path/to/project/packages/bar/bar.js
import { findPackageJSON } from 'node:module';

findPackageJSON('..', import.meta.url);
// '/path/to/project/package.json'
// Same result when passing an absolute specifier instead:
findPackageJSON(new URL('../', import.meta.url));
findPackageJSON(import.meta.resolve('../'));

findPackageJSON('some-package', import.meta.url);
// '/path/to/project/packages/bar/node_modules/some-package/package.json'
// When passing an absolute specifier, you might get a different result if the
// resolved module is inside a subfolder that has nested `package.json`.
findPackageJSON(import.meta.resolve('some-package'));
// '/path/to/project/packages/bar/node_modules/some-package/some-subfolder/package.json'

findPackageJSON('@foo/qux', import.meta.url);
// '/path/to/project/packages/qux/package.json'
// /path/to/project/packages/bar/bar.js
const { findPackageJSON } = require('node:module');
const { pathToFileURL } = require('node:url');
const path = require('node:path');

findPackageJSON('..', __filename);
// '/path/to/project/package.json'
// Same result when passing an absolute specifier instead:
findPackageJSON(pathToFileURL(path.join(__dirname, '..')));

findPackageJSON('some-package', __filename);
// '/path/to/project/packages/bar/node_modules/some-package/package.json'
// When passing an absolute specifier, you might get a different result if the
// resolved module is inside a subfolder that has nested `package.json`.
findPackageJSON(pathToFileURL(require.resolve('some-package')));
// '/path/to/project/packages/bar/node_modules/some-package/some-subfolder/package.json'

findPackageJSON('@foo/qux', __filename);
// '/path/to/project/packages/qux/package.json'
M

module.isBuiltin

History
module.isBuiltin(moduleName): boolean
Attributes
moduleName:string
name of the module
Returns:boolean
returns true if the module is builtin else returns false
import { isBuiltin } from 'node:module';
isBuiltin('node:fs'); // true
isBuiltin('fs'); // true
isBuiltin('wss'); // false
module.register(specifier, parentURL?, options?): void
Stability: 0Deprecated: Use module.registerHooks() instead.
Attributes
specifier:string | URL
Customization hooks to be registered; this should be the same string that would be passed to import(), except that if it is relative, it is resolved relative to parentURL.
parentURL?:string | URL
If you want to resolve specifier relative to a base URL, such as import.meta.url, you can pass that URL here. Default: 'data:'
options:Object
parentURL?:string | URL
If you want to resolve specifier relative to a base URL, such as import.meta.url, you can pass that URL here. This property is ignored if the parentURL is supplied as the second argument. Default: 'data:'
data:any
Any arbitrary, cloneable JavaScript value to pass into the initialize hook.
transferList:Object[]
transferable objects to be passed into the initialize hook.

Register a module that exports hooks that customize Node.js module resolution and loading behavior. See Customization hooks.

This feature requires --allow-worker if used with the Permission Model.

module.registerHooks(options): Object
Stability: 1.2Release candidate
Attributes
options:Object
See load hook. Default: undefined.
resolve?:Function | undefined
See resolve hook. Default: undefined.
Returns:Object
An object with the following property:

Register hooks that customize Node.js module resolution and loading behavior. See Customization hooks. The returned object can be used to deregister the hooks.

M

module.stripTypeScriptTypes

History
module.stripTypeScriptTypes(code, options?): string
Stability: 1.2Release candidate
Attributes
code:string
The code to strip type annotations from.
options:Object
mode?:string
Default: 'strip'. Possible values are:
'strip':
Only strip type annotations without performing the transformation of TypeScript features.
sourceUrl:string
Specifies the source url used in the source map.
Returns:string
The code with type annotations stripped.

module.stripTypeScriptTypes() removes type annotations from TypeScript code. It can be used to strip type annotations from TypeScript code before running it with vm.runInContext() or vm.compileFunction().

By default, it will throw an error if the code contains TypeScript features that require transformation, such as enums. See type-stripping for more information.

WARNING: The output of this function should not be considered stable across Node.js versions, due to changes in the TypeScript parser.

import { stripTypeScriptTypes } from 'node:module';
const code = 'const a: number = 1;';
const strippedCode = stripTypeScriptTypes(code);
console.log(strippedCode);
// Prints: const a         = 1;
const { stripTypeScriptTypes } = require('node:module');
const code = 'const a: number = 1;';
const strippedCode = stripTypeScriptTypes(code);
console.log(strippedCode);
// Prints: const a         = 1;

If sourceUrl is provided, it will be used appended as a comment at the end of the output:

import { stripTypeScriptTypes } from 'node:module';
const code = 'const a: number = 1;';
const strippedCode = stripTypeScriptTypes(code, { mode: 'strip', sourceUrl: 'source.ts' });
console.log(strippedCode);
// Prints: const a         = 1\n\n//# sourceURL=source.ts;
const { stripTypeScriptTypes } = require('node:module');
const code = 'const a: number = 1;';
const strippedCode = stripTypeScriptTypes(code, { mode: 'strip', sourceUrl: 'source.ts' });
console.log(strippedCode);
// Prints: const a         = 1\n\n//# sourceURL=source.ts;
M

module.syncBuiltinESMExports

History
module.syncBuiltinESMExports(): void

The module.syncBuiltinESMExports() method updates all the live bindings for builtin ES Modules to match the properties of the CommonJS exports. It does not add or remove exported names from the ES Modules.

const fs = require('node:fs');
const assert = require('node:assert');
const { syncBuiltinESMExports } = require('node:module');

fs.readFile = newAPI;

delete fs.readFileSync;

function newAPI() {
  // ...
}

fs.newAPI = newAPI;

syncBuiltinESMExports();

import('node:fs').then((esmFS) => {
  // It syncs the existing readFile property with the new value
  assert.strictEqual(esmFS.readFile, newAPI);
  // readFileSync has been deleted from the required fs
  assert.strictEqual('readFileSync' in fs, false);
  // syncBuiltinESMExports() does not remove readFileSync from esmFS
  assert.strictEqual('readFileSync' in esmFS, true);
  // syncBuiltinESMExports() does not add names
  assert.strictEqual(esmFS.newAPI, undefined);
});