Skip to content

Commit

Permalink
module: add isBuiltIn method
Browse files Browse the repository at this point in the history
PR-URL: #43396
Fixes: #42785
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Ruben Bridgewater <ruben@bridgewater.de>
Reviewed-By: Michaël Zasso <targos@protonmail.com>
Reviewed-By: Anto Aravinth <anto.aravinth.cse@gmail.com>
Reviewed-By: Juan José Arboleda <soyjuanarbol@gmail.com>
  • Loading branch information
hemanth authored and targos committed Jul 12, 2022
1 parent c9f130e commit 9d918d9
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 0 deletions.
16 changes: 16 additions & 0 deletions doc/api/module.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,22 @@ const require = createRequire(import.meta.url);
const siblingModule = require('./sibling-module');
```
### `module.isBuiltin(moduleName)`
<!-- YAML
added: REPLACEME
-->
* `moduleName` {string} name of the module
* Returns: {boolean} returns true if the module is builtin else returns false
```mjs
import { isBuiltin } from 'node:module';
isBuiltin('node:fs'); // true
isBuiltin('fs'); // true
isBuiltin('wss'); // false
```
### `module.syncBuiltinESMExports()`
<!-- YAML
Expand Down
11 changes: 11 additions & 0 deletions lib/internal/modules/cjs/loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ const {
ArrayPrototypeSplice,
ArrayPrototypeUnshift,
ArrayPrototypeUnshiftApply,
ArrayPrototypeFlatMap,
Boolean,
Error,
JSONParse,
Expand All @@ -50,6 +51,7 @@ const {
ReflectSet,
RegExpPrototypeExec,
SafeMap,
SafeSet,
SafeWeakMap,
String,
StringPrototypeCharAt,
Expand Down Expand Up @@ -186,6 +188,11 @@ for (const { 0: id, 1: mod } of NativeModule.map) {
}
}

const allBuiltins = new SafeSet(
ArrayPrototypeFlatMap(builtinModules, (bm) => [bm, `node:${bm}`])
);
NativeModule.getSchemeOnlyModuleNames().forEach((builtin) => allBuiltins.add(`node:${builtin}`));

ObjectFreeze(builtinModules);
Module.builtinModules = builtinModules;

Expand Down Expand Up @@ -1300,5 +1307,9 @@ Module.syncBuiltinESMExports = function syncBuiltinESMExports() {
}
};

Module.isBuiltin = function isBuiltin(moduleName) {
return allBuiltins.has(moduleName);
};

// Backwards compatibility
Module.Module = Module;
16 changes: 16 additions & 0 deletions test/parallel/test-module-isBuiltin.js
Original file line number Diff line number Diff line change
@@ -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'));
assert(isBuiltin('node:fs'));
assert(isBuiltin('node:test'));

// Does not include internal modules
assert(!isBuiltin('internal/errors'));
assert(!isBuiltin('test'));
assert(!isBuiltin(''));
assert(!isBuiltin(undefined));

0 comments on commit 9d918d9

Please sign in to comment.