Valu3
Valu3

Reputation: 434

NodeJS - Dynamically import built in modules

I'd like to get a built in module (for example Math or path or fs), whether from the global object or require, I thought about doing something like this:

function getModuleByName(name) {
     return global[name] || require(name);
}

Is there a way to check that it is indeed a module and not something else? Would this make a security problem?

Upvotes: 1

Views: 1462

Answers (1)

jmcgrory
jmcgrory

Reputation: 843

Is there a way to check that it is indeed a module and not something else?

Other methods but here's an example:

function getModuleByName(name)
{
  let module = null;
  try {
    module = require(name);
  } catch (e) {
     // Recommend Logging e Somewhere
  }
  return module;
}

This will graciously fail as null where the module does not exist, or return it.

Would this make a security problem?

Quite possibly, it depends on how it's used. I'd argue it is more of a general design issue however and would blanket say avoid doing it (without any context, you may have a very good reason).

You, like anyone, obviously have a finite amount of modules you could be loading. These modules have all been selected by yourself for your application for specific reasons, or are bundled into your node version natively and are expected parts of your environment.

What you are doing by introducing this functionality is adding the addition of unexpected elements in your environment. If you are using getModuleByName to access a third party library- you should know outright that library is available and as such there's no reason why you can't just require it directly.

--

If you do think your use case warrants this, please let me know what it is as I may never have encountered it before. I have used dynamic imports like the following:

https://javascript.info/modules-dynamic-imports

But that hasn't been for global packages/libraries, but for dynamic reference to modules built internally to the application (i.e. routing to different views, invokation of internal scripts).

These I have protected by ensuring filepaths can't be altered by whitelisting the target directories, making sure each script follows a strict interface per use case and graciously failing where a module doesn't exist (error output "this script does not exist" for the script usage and a 404 view for the routing example).

Upvotes: 2

Related Questions