Require file somewhere in the directory node.js

I have a file that is required in many other files, that are on different folders, inside the main directory.

Is there a way to just require the filename without having to write the relative path, or the absolute path? Like require('the_file'). And without having to go to npm and install it?

Create a folder inside your main directory , put the_file.js inside and set the NODE_PATH variable to this folder.

Example :

Let's say you create a ./libs folder within your main directory, you can just use :

export NODE_PATH = /.../main/lib

after that, you can require any module inside this directory using just :

var thefile = require('the_file')

To not have to do that every time, you'd have to add the variable to your .bashrc (assuming you're running a Unix system).

Or you can set a global variable inside your app.js file and store the path of your 'the_file' in it like so :

global.rootPath = __dirname;

Then you can require from any of your files using :

var thefile = require(rootPath+'/the_file')

These are the most convenient methods for me, short of creating a private npm, but there are a few other alternatives that I discovered when looking up an answer to your question, have a look here : https://gist.github.com/branneman/8048520