'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");
Solution 1:[1]
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');
Solution 2:[2]
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.
Solution 3:[3]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Peter Lyons |
Solution 3 | Alan Omar |