Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save aprilmintacpineda/66f6095ea7a9228db692a6dc794b19cb to your computer and use it in GitHub Desktop.
Save aprilmintacpineda/66f6095ea7a9228db692a6dc794b19cb to your computer and use it in GitHub Desktop.
NodeJS require concept for local modules

The simplest solution I thought of:

on the top of your server.js or whatever the filename is of that which you run first when you startup your nodejs application.

const path = require('path');
global._require = module => require(path.join(__dirname, module));

Then on a/very/far/away/module.js:

const validator = _require('libs/validator');
// coming from the /root
const { validListOfThings } = require('constants');

The file structure would look like:

/root
|- a
|  |- very
|  |  |- far
|  |  |  |- away
|  |  |  |  |- module.js
|- libs
|  |- validator.js
|- server.js
|- constants.js

You can now use _require for your local modules, and you can still use require for your node_modules.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment