diff --git a/doc/api/modules.md b/doc/api/modules.md index 5ceda7c1ff3fd6..52e2a24d593a1d 100644 --- a/doc/api/modules.md +++ b/doc/api/modules.md @@ -633,5 +633,29 @@ object. Since `require()` returns the `module.exports`, and the `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 [module resolution]: #modules_all_together diff --git a/lib/module.js b/lib/module.js index 537a2dcafb31d0..3b258f051bd4ca 100644 --- a/lib/module.js +++ b/lib/module.js @@ -48,9 +48,16 @@ function Module(id, parent) { } module.exports = Module; +const builtinModules = Object.keys(NativeModule._source) + .filter(NativeModule.nonInternalExists); + +Object.freeze(builtinModules); +Module.builtinModules = builtinModules; + Module._cache = {}; Module._pathCache = {}; Module._extensions = {}; + var modulePaths = []; Module.globalPaths = []; 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/')), + [] +);