Skip to content
Merged
Show file tree
Hide file tree
Changes from 20 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)`
Comment thread
hemanth marked this conversation as resolved.
Outdated

<!-- 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';
Comment thread
hemanth marked this conversation as resolved.
Outdated
isBuiltIn('node:fs'); // true
Comment thread
hemanth marked this conversation as resolved.
Outdated
isBuiltIn('fs'); // true
isBuiltIn('wss'); // false
```

### `module.syncBuiltinESMExports()`

<!-- YAML
Expand Down
10 changes: 10 additions & 0 deletions lib/internal/modules/cjs/loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ const {
RegExpPrototypeExec,
RegExpPrototypeTest,
SafeMap,
SafeSet,
SafeWeakMap,
String,
StringPrototypeCharAt,
Expand Down Expand Up @@ -188,6 +189,11 @@ for (const { 0: id, 1: mod } of NativeModule.map) {
}
}

let allBuiltins = builtinModules.slice();
builtinModules.forEach((builtin) => allBuiltins.push(`node:${builtin}`));
allBuiltins = new SafeSet(allBuiltins);
NativeModule.getSchemeOnlyModuleNames().forEach((builtin) => allBuiltins.add(`node:${builtin}`));
Comment thread
hemanth marked this conversation as resolved.
Outdated

ObjectFreeze(builtinModules);
Module.builtinModules = builtinModules;

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

Module.isBuiltIn = function isBuiltIn(moduleName) {
Comment thread
hemanth marked this conversation as resolved.
Outdated
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'));
Comment thread
hemanth marked this conversation as resolved.
Outdated
assert(isBuiltIn('node:fs'));
assert(isBuiltIn('node:test'));

Comment thread
hemanth marked this conversation as resolved.
Outdated
// Does not include internal modules
assert(!isBuiltIn('internal/errors'));
assert(!isBuiltIn('test'));
assert(!isBuiltIn(''));
assert(!isBuiltIn(undefined));