kasun kavinda
kasun kavinda

Reputation: 71

How to look for a specific folder with require in node js

enter image description hereI need to require() method to load modules from a folder nonother that node_modules folder. Is there a way to do that without using any npm libraries.

EX- There is an age folder inside the modules folder with an index.js file. I need to import that module like

const age = require('age')

without giving the relative path of the module.

Upvotes: 1

Views: 544

Answers (1)

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276596

Is there a way to do that without using any npm libraries.

The answer to that sort of thing is always "yes" because those libraries are written in JavaScript.

I would warmly recommend against it and for standard approaches (like using yarn workspaces and declaring age as a proper local npm module) but you can always do something like a require hook:

const originalRequire = Module.prototype.require;
Module.prototype.require = function moduleRequire(id) {
  if(id === 'age') {
    return require('./modules/age');
  }
  return originalRequire.call(this, id);
}

Or add your local modules folder to the NODE_PATH environment variable so it finds it there.

Neither of these are good options and I recommend against both of them.

It is better to stick to the standard modus operandi and vendor and consume "proper" npm modules.

Upvotes: 1

Related Questions