Node TAP
    Preparing search index...

    A child class of Module, which loads modules from the mock object if specified, otherwise will load unmocked modules in its own mocked environment, so that they will load the mocked modules as well.

    Hierarchy (View Summary)

    Index

    Constructors

    Properties

    children: Module[]

    The module objects required for the first time by this one.

    v0.1.16

    exports: any

    The module.exports object is created by the Module system. Sometimes this is not acceptable; many want their module to be an instance of some class. To do this, assign the desired export object to module.exports.

    v0.1.16

    filename: string

    The fully resolved filename of the module.

    v0.1.16

    id: string

    The identifier for the module. Typically this is the fully resolved filename.

    v0.1.16

    isPreloading: boolean

    true if the module is running during the Node.js preload phase.

    v15.4.0, v14.17.0

    loaded: boolean

    Whether or not the module is done loading, or is in the process of loading.

    v0.1.16

    parent: undefined | null | Module

    The module that first required this one, or null if the current module is the entry point of the current process, or undefined if the module was loaded by something that is not a CommonJS module (e.g. REPL or import).

    v0.1.16

    Please use require.main and module.children instead.

    path: string

    The directory name of the module. This is usually the same as the path.dirname() of the module.id.

    v11.14.0

    paths: string[]

    The search paths for the module.

    v0.4.0

    _cache: { [k: string]: CorrectModule }
    builtinModules: readonly 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.

    Note: the list doesn't contain prefix-only modules like node:test.

    v9.3.0, v8.10.0, v6.13.0

    constants: typeof constants
    createRequire: (path: string | URL) => Require

    Type Declaration

      • (path: string | URL): Require
      • Parameters

        • path: 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

        v12.2.0

    enableCompileCache: (cacheDir?: string) => EnableCompileCacheResult

    Type Declaration

      • (cacheDir?: string): EnableCompileCacheResult
      • Enable module compile cache in the current Node.js instance.

        If cacheDir is not specified, Node.js will either use the directory specified by the NODE_COMPILE_CACHE=dir environment variable if it's set, or use path.join(os.tmpdir(), 'node-compile-cache') otherwise. For general use cases, it's recommended to call module.enableCompileCache() without specifying the cacheDir, so that the directory can be overridden by the NODE_COMPILE_CACHE environment variable when necessary.

        Since compile cache is supposed to be a quiet optimization that is not required for the application to be functional, this method is designed to not throw any exception when the compile cache cannot be enabled. Instead, it will return an object containing an error message in the message field to aid debugging. If compile cache is enabled successfully, the directory field in the returned object contains the path to the directory where the compile cache is stored. The status field in the returned object would be one of the module.constants.compileCacheStatus values to indicate the result of the attempt to enable the module compile cache.

        This method only affects the current Node.js instance. To enable it in child worker threads, either call this method in child worker threads too, or set the process.env.NODE_COMPILE_CACHE value to compile cache directory so the behavior can be inherited into the child workers. The directory can be obtained either from the directory field returned by this method, or with getCompileCacheDir.

        Parameters

        • OptionalcacheDir: string

          Optional path to specify the directory where the compile cache will be stored/retrieved.

        Returns EnableCompileCacheResult

        v22.8.0

    findPackageJSON: (
        specifier: string | URL,
        base?: string | URL,
    ) => undefined | string

    Type Declaration

      • (specifier: string | URL, base?: string | URL): undefined | string
      • /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'

        Parameters

        • 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.

        • Optionalbase: 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 undefined | string

        A path if the package.json is found. When startLocation is a package, the package's root package.json; when a relative or unresolved, the closest package.json to the startLocation.

        v22.14.0

    findSourceMap: (path: string) => undefined | SourceMap

    Type Declaration

      • (path: string): undefined | SourceMap
      • path is the resolved path for the file for which a corresponding source map should be fetched.

        Parameters

        • path: string

        Returns undefined | SourceMap

        Returns module.SourceMap if a source map is found, undefined otherwise.

        v13.7.0, v12.17.0

    flushCompileCache: () => void

    Type Declaration

      • (): void
      • Flush the module compile cache accumulated from modules already loaded in the current Node.js instance to disk. This returns after all the flushing file system operations come to an end, no matter they succeed or not. If there are any errors, this will fail silently, since compile cache misses should not interfere with the actual operation of the application.

        Returns void

        v22.10.0

    getCompileCacheDir: () => undefined | string

    Type Declaration

      • (): undefined | string
      • Returns undefined | string

        Path to the module compile cache directory if it is enabled, or undefined otherwise.

        v22.8.0

    getSourceMapsSupport: () => SourceMapsSupport

    Type Declaration

      • (): SourceMapsSupport
      • This method returns whether the Source Map v3 support for stack traces is enabled.

        Returns SourceMapsSupport

        v23.7.0, v22.14.0

    isBuiltin: (moduleName: string) => boolean

    Type Declaration

      • (moduleName: string): boolean
      • Parameters

        • moduleName: string

        Returns boolean

        v18.6.0, v16.17.0

    Module: typeof Module
    register: {
        <Data = any>(
            specifier: string | URL,
            parentURL?: string | URL,
            options?: RegisterOptions<Data>,
        ): void;
        <Data = any>(
            specifier: string | URL,
            options?: RegisterOptions<Data>,
        ): void;
    }

    Type Declaration

      • <Data = any>(
            specifier: string | URL,
            parentURL?: string | URL,
            options?: RegisterOptions<Data>,
        ): void
      • 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.

        Type Parameters

        • Data = any

        Parameters

        • 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.

        • OptionalparentURL: string | URL

          f you want to resolve specifier relative to a base URL, such as import.meta.url, you can pass that URL here.

        • Optionaloptions: RegisterOptions<Data>

        Returns void

        v20.6.0, v18.19.0

      • <Data = any>(specifier: string | URL, options?: RegisterOptions<Data>): void
      • 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.

        Type Parameters

        • Data = any

        Parameters

        • 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.

        • Optionaloptions: RegisterOptions<Data>

        Returns void

        v20.6.0, v18.19.0

    registerHooks: (options: RegisterHooksOptions) => ModuleHooks

    Type Declaration

      • (options: RegisterHooksOptions): ModuleHooks
      • Experimental

        Register hooks that customize Node.js module resolution and loading behavior.

        Parameters

        • options: RegisterHooksOptions

        Returns ModuleHooks

        v22.15.0

    runMain: (main?: string) => void
    setSourceMapsSupport: (
        enabled: boolean,
        options?: SetSourceMapsSupportOptions,
    ) => void

    Type Declaration

      • (enabled: boolean, options?: SetSourceMapsSupportOptions): void
      • This function enables or disables the Source Map v3 support for stack traces.

        It provides same features as launching Node.js process with commandline options --enable-source-maps, with additional options to alter the support for files in node_modules or generated codes.

        Only source maps in JavaScript files that are loaded after source maps has been enabled will be parsed and loaded. Preferably, use the commandline options --enable-source-maps to avoid losing track of source maps of modules loaded before this API call.

        Parameters

        • enabled: boolean
        • Optionaloptions: SetSourceMapsSupportOptions

        Returns void

        v23.7.0, v22.14.0

    SourceMap: typeof SourceMap
    stripTypeScriptTypes: (
        code: string,
        options?: StripTypeScriptTypesOptions,
    ) => string

    Type Declaration

      • (code: string, options?: StripTypeScriptTypesOptions): string
      • 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. When mode is 'transform', it also transforms TypeScript features to JavaScript, see transform TypeScript features for more information. When mode is 'strip', source maps are not generated, because locations are preserved. If sourceMap is provided, when mode is 'strip', an error will be thrown.

        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;

        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;

        When mode is 'transform', the code is transformed to JavaScript:

        import { stripTypeScriptTypes } from 'node:module';
        const code = `
        namespace MathUtil {
        export const add = (a: number, b: number) => a + b;
        }`;
        const strippedCode = stripTypeScriptTypes(code, { mode: 'transform', sourceMap: true });
        console.log(strippedCode);
        // Prints:
        // var MathUtil;
        // (function(MathUtil) {
        // MathUtil.add = (a, b)=>a + b;
        // })(MathUtil || (MathUtil = {}));
        // # sourceMappingURL=data:application/json;base64, ...

        Parameters

        • code: string

          The code to strip type annotations from.

        • Optionaloptions: StripTypeScriptTypesOptions

        Returns string

        The code with type annotations stripped.

        v22.13.0

    syncBuiltinESMExports: () => void

    Type Declaration

      • (): 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.

        import fs from 'node:fs';
        import assert from 'node:assert';
        import { syncBuiltinESMExports } from '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);
        });

        Returns void

        v12.12.0

    wrap: (script: string) => string

    Methods

    • Override require() to perform our mocked require

      Parameters

      • id: string

      Returns any