Gabriel Llamas
Gabriel Llamas

Reputation: 18427

Check if the required module is a built-in module

I need to check if the module that is going to be loaded is a built-in or an external module. For example, suppose that you have a module named fs inside the node_modules directory. If you do require("fs") the built-in module will be loaded instead of the module inside node_modules, so I'm sure that this question has a solution.

Example:

var loadModule = function (moduleName){
  if (isCoreModule (moduleName)){
    ...
  }else{
    ...
  }
};

loadModule ("fs");

Upvotes: 1

Views: 1125

Answers (4)

Time Killer
Time Killer

Reputation: 846

Module.isBuiltin Added in: v18.6.0, v16.17.0

import { isBuiltin } from 'node:module';
isBuiltin('node:fs'); // true
isBuiltin('fs'); // true
isBuiltin('fs/promises'); // true
isBuiltin('wss'); // false

Upvotes: 2

Alan Omar
Alan Omar

Reputation: 4217

you can use require.resolve.paths(str):

1- if str is core module the call will return null.

2- if str is not core module you will get an array of strings.

Upvotes: 3

mscdex
mscdex

Reputation: 106696

process.binding('natives'); returns an object that provides access to all built-in modules, so getting the keys of this object will get you the module names. So you could simply do something like:

var nativeModules = Object.keys(process.binding('natives'));

function loadModule(name) {
  if (~nativeModules.indexOf(name)) {
    // `name` is a native module name
  } else {
    // ...
  }
};

loadModule('fs');

Upvotes: 6

Peter Lyons
Peter Lyons

Reputation: 146064

My first attempt would be: require.resolve(moduleName).indexOf('/') <= 0. If that is true, it's a core module. Might not be portable to windows as implemented, but you should be able to use this idea to get going in the right direction.

Aside: beware require.resolve does synchronous filesystem IO. Be careful about using it within a network server.

Aside: Careful with the term "native" which generally means a native-code compiled add-on, or a C/C++ implementation. Both "core" and community modules can be either pure JS or native. I think "core" is the most accurate term for built-in modules.

Aside: best not to shadow global variable names, so moduleName instead of just module which can be confusing with the global of the same name.

Upvotes: 1

Related Questions