Nodejs – Dependency Management

Introduction

An Important concept, in Node.js is that you want to know the way dependency management is handled. This dependency management is the part of core Node.js experience. In this post, we will learn various pattern of dependency management and how Nodejs load dependencies.

So, we could write our application using a single js file for everything, but that’s not modular. Node.js makes it very simple to write modular code.

Before we dive into the details , the first question to answer , the module. What is it? And why should we care about it?

In simple terms, a module is code, that we group together, for the purposes of sharing and reuse. Modules, therefore, allow us to break down complexity in our applications into small chunks. This can help with understanding the code right down to finding and fixing bugs. If you want to know more about JavaScript Module systems, you can check this post.

Node uses a facility for requiring certain behaviors. This is based on CommonJS. In short to bring a JavaScript file, we use the keyword require.

I am assuming that you already know some basics of Nodejs. You can also check my earlier post Node.js – Introduction for some background information if you are new to Nodejs.

Setting Up the Application

Let’s start simple. I’ve created a directory for the project, used npm init to initialize it and created two JavaScript files (app.js and appMsg.js). This is how to project looks like and we will use this as a starting point for the demos. Also you can download the final code from git repo link mentioned later in the post.

At this point, both js files are empty. Let’s update appMsgs.js file with the following changes:

we can see the use of module.exports keyword. This syntax is used to expose properties or objects from a given file (appMsgs.js) which can be then used in another file and in our case that will be app.js.

In this system each file has access to something called the module.exports. So, we exposed some items in appMsgs.js file and now Let’s see how app.js can use (require) these properties:

Now to reference a file, we use the require keyword. When we require, it is going to return an object that’s going to represent that modular piece of code, so we assign this to a variable appMsgs variable and then simply used properties in console.log statements. When we execute the code, we can see the following output:

So, this require is executing the JavaScript, allowing it to construct an object that had returned to us has some functionality.

This could be a class constructor, or an object that has number of elements in it or some plain simple properties. There are different patterns for this and we can export more than one thing or even export complex objects.

So by managing require, as well as module.exports, we can create these modular applications.

The require functionality loads the code and loads it once. So, whatever code is executed here, this is never executed a second timed. So, if someone else asked for this object by require, it’s going to get a cached version of this. Let’s look at some other ways.

I have changed the code and now instead of exposing an object, it is exporting a function. This code is executed every time when called as a function.

Let’s see how it is used in app.js file next:

Instead of calling a property, we can just execute it, like a function. So, the difference here is that every time we execute this code, the code inside the function is re-executed.

Here is the output when we run the code:

So, we have seen two patterns of module.exports and their difference. Another common pattern, you’re going to want to be aware of using this as a constructor method. Let’s see an example of that:

and here is the updated app.js file:

So, this is in essence is same thing as when you’re creating a pseudo class in JavaScript and allowing you to create instances of it.

Here is the output of this change:

Now, lets see another example of these patterns:

I have created a new file called userRepo.js as follows:

and here is app.js and execution result for this change:

using require for individual files is not uncommon but there is also another pattern you should be aware of. Let’s see folder dependencies next.

Folder Dependency

We will take a step back and understand how Nodejs looks for dependencies. Remember the line from earlier examples:

var appMsgs = require("./appMsgs")

Node would still look for appMsgs.js file, but also it would look for appMsgs as a directory and whichever it found first, it would pull that in.

Now let’s see the code:

I have created a folder called logger and inside that folder I created a file index.js.

Here is the code from index.js file:

and here is the app.js file which requires this module:

So, in our case we could say:

var logger = require("./logger/index.js")

and that would be perfectly valid. But instead, by just saying the following:

var logger = require("./logger")

since there isn’t a logger.js, there’s a logger directory, its going to by default, load the index.js as the starting point for our logger. That’s why I gave the name index.js and let’s see what is the result of executing this code:

So, on its own you might think, well why bother going through this extra step of creating a folder and an inex.js ?

And the reason for that is you may be putting together a complex dependency and this dependency may have other pieces it depends on. The caller that needs the logger doesn’t need to know that there’s a bunch of these other dependences.

This is a form of encapsulation, so that as we are building more complex pieces, we can build them out of multiple files. Then on consumer side, use a single file. It just implies that a folder is good way to manage those sort of dependencies.

Node Package Manager (NPM)

One more thing we want to discuss briefly is NPM. You might already know its purpose. This brings in additional functionality and its usage is very straight forward.

we can install a dependency using npm:

npm install underscore;

and then can simply require it in app.js as follows:

and you can see now we can use functionality offered by underscore package. Also when we required this module, we didn’t specified the file path, we just use its name and Nodejs will load this module from node_modules folder in your application.

here is output of the execution:

Summary

In this post we learnt how Nodejs manage its dependencies and we saw few patterns to use in our application. You can download the source-code from this Git repository. Let me know if you have some questions or comments. Till next time, Happy Coding.

My Recent Books

1 thought on “Nodejs – Dependency Management”

Comments are closed.