diff --git a/doc/api/modules.md b/doc/api/modules.md index 50fda3591f102b..cdb591563ce649 100644 --- a/doc/api/modules.md +++ b/doc/api/modules.md @@ -819,6 +819,28 @@ The `module.require` method provides a way to load a module as if `module` is typically *only* available within a specific module's code, it must be explicitly exported in order to be used. +## The `Module` Object + + + +* {Object} + +Provides general utility methods when interacting with instances of +`Module` -- the `module` variable often seen in file modules. Accessed +via `require('module')`. + +### module.builtinModules + + +* {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 module or not. + [`__dirname`]: #modules_dirname [`__filename`]: #modules_filename [`Error`]: errors.html#errors_class_error diff --git a/lib/module.js b/lib/module.js index ac055f8154ed46..c96d5d51678494 100644 --- a/lib/module.js +++ b/lib/module.js @@ -76,6 +76,12 @@ function Module(id, parent) { this.children = []; } +const builtinModules = Object.keys(NativeModule._source) + .filter(NativeModule.nonInternalExists); + +Object.freeze(builtinModules); +Module.builtinModules = builtinModules; + Module._cache = Object.create(null); Module._pathCache = Object.create(null); Module._extensions = Object.create(null); diff --git a/test/parallel/test-module-builtin.js b/test/parallel/test-module-builtin.js new file mode 100644 index 00000000000000..3897d71ecf4405 --- /dev/null +++ b/test/parallel/test-module-builtin.js @@ -0,0 +1,14 @@ +'use strict'; +require('../common'); +const assert = require('assert'); +const { builtinModules } = require('module'); + +// Includes modules in lib/ (even deprecated ones) +assert(builtinModules.includes('http')); +assert(builtinModules.includes('sys')); + +// Does not include internal modules +assert.deepStrictEqual( + builtinModules.filter((mod) => mod.startsWith('internal/')), + [] +);