From a66a302b63f50e05654542e575c58f45d1596b4d Mon Sep 17 00:00:00 2001 From: "hemanth.hm" Date: Tue, 14 Jun 2022 00:29:33 +0000 Subject: [PATCH] module: add isBuiltIn method --- lib/internal/modules/cjs/loader.js | 6 ++++++ test/parallel/test-module-isBuiltIn.js | 16 ++++++++++++++++ 2 files changed, 22 insertions(+) create mode 100644 test/parallel/test-module-isBuiltIn.js diff --git a/lib/internal/modules/cjs/loader.js b/lib/internal/modules/cjs/loader.js index b7fc3f9b2a1ea5..3c88c0e543be97 100644 --- a/lib/internal/modules/cjs/loader.js +++ b/lib/internal/modules/cjs/loader.js @@ -191,6 +191,7 @@ for (const { 0: id, 1: mod } of NativeModule.map) { ObjectFreeze(builtinModules); Module.builtinModules = builtinModules; + Module._cache = ObjectCreate(null); Module._pathCache = ObjectCreate(null); Module._extensions = ObjectCreate(null); @@ -1293,5 +1294,10 @@ Module.syncBuiltinESMExports = function syncBuiltinESMExports() { } }; +Module.isBuiltIn = function isBuiltIn(moduleName) { + moduleName = String(moduleName).replace('node:', ''); + return Module.builtinModules.includes(moduleName); +}; + // Backwards compatibility Module.Module = Module; diff --git a/test/parallel/test-module-isBuiltIn.js b/test/parallel/test-module-isBuiltIn.js new file mode 100644 index 00000000000000..96d32efa44a748 --- /dev/null +++ b/test/parallel/test-module-isBuiltIn.js @@ -0,0 +1,16 @@ +'use strict'; +require('../common'); +const assert = require('assert'); +const { isBuiltIn } = require('module'); + +// Includes modules in lib/ (even deprecated ones) +assert(isBuiltIn('http')); +assert(isBuiltIn('sys')); + +// Does not include internal modules +assert(!isBuiltIn('internal')); +assert(!isBuiltIn('')); +assert(!isBuiltIn(undefined)); + + +