1

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.

3
  • Please show us the EXACT folder structure you're trying to load from. Otherwise see the doc nodejs.org/api/… for the other places node.js will load from without a path. Commented Dec 16, 2019 at 8:13
  • 1
    My answer would to not create this problem for yourself in the first place. Either place the modules in an expected node_modules location, in an expected global location or use a path to indicate where to load it from. Commented Dec 16, 2019 at 8:22
  • 1
    Your answer for how require() works is all in that doc reference I gave you. If you want just require('age') to find it, I think you will have to put its path in NODE_PATH or replace/hook require() to give it new behaviors. Based on the doc, I don't see any other way. I would argue that you're doing something wrong in your design when you have this problem. This is not how node.js was built to run and you're trying to sub-vert it somehow. Commented Dec 16, 2019 at 8:29

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.