Modules are the nodejs way of doing things bigger and easier, rather than spending time on trivial problems which has been already solved and optimized. If you’re someone like me, coming from a programming background of C/C++, PHP or Python, you’d find yourself totally adaptable to the idea of it. You’d find it analogous to header files of C/C++ or packages of Java.
There is a big community working behind nodejs, and these people are making sure that day to day problems are brought up with generic solutions that can help developers concentrate more on the project rather than the solving complexities with nodejs.
Coming back to modules, there can be categorized in two segments, core modules and user modules, these names are self-explanatory. While core modules come bundled with the official tarball of nodejs, it is the user modules that form the bulk. The official nodejs bundle comes with only those (core) modules which are used extensively by most of the users or if they are form the most essential piece of the art. Ex. http module is a core module used for setting up a http web server using nodejs. User modules are provided through third party support or individual contributors from the community. Ex. Express is a web framework for nodejs. User modules are published through a great utillity NPM ( Node Package Manager ). The official tarball from github comes bundled with NPM so you don’t have to worry about that.
Installing any user modules is a piece of cake using npm.
npm install <modulename>
However, it is to be noted that this module is installed locally for the given directory/project, and in that case it won’t be available for other projects. In this case npm installs it by creating a directory node_modules.
To install it globally use the -g paramater.
npm install -g <modulename>
To use a module within your project you simply need to write the following command
It’s a convention to use the variable name same as that of the modulename, however you can use any random stuff there. Node looks for the module with a priority given to the core modules, then if it doesn’t find a module there, it’ll look within the node_modules directory, if even in that case nodejs fails, then it moves recursively upward in the directory hierarchy looking for the specified modulename . After all this effort, if there is still no success, then node throws an error, and your program will halt eventually.
Any queries ? Shout me @anathema_imbued or mail me : email@example.com