Sunday, October 18, 2015

Using Symbolic Links for Modules in Node.js

To avoid the relative directory nightmare in Node.js, a simple operating system hack can be used to bypass the problem. Rather than referencing your module as:

 var mymodule = require('../../../mymodule')  

a simple trick with symbolic links can be used to reference your module as:

 var mymodule = require('_/mymodule')  

from anywhere within your project.

First create a library directory (lib) within your project, and move your module within this directory. To create a symbolic link, perform the following process from a command window:

Linux and Mac:

 cd /myproject/node_modules
 ln -s ../lib _

Windows:

 cd /myproject/node_modules
 mklink /D _ ..\lib

There is nothing magical about the underscore character;  Any name could be used to reference your directory, however, picking something innocuous will help prevent name collisions with other modules imported into your project.