Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore.

15 St Margarets, NY 10033
(+381) 11 123 4567



Node.js – Dependency Management – DZone Web Dev


An important concept in Node.js is that you want to know the way dependency management is handled. This dependency management is part of the core Node.js experience. In this post, we will learn the various patterns 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 a 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 the git repo link mentioned later in the post.

Created 2 JavaScript Files

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

We can see the use of the 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 the appMsgs.js file and now Let’s see how app.js can use (require) these properties:

Adding Require

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:

Code Execution 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 a 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 required functionality loads the code and loads it once. So, whatever code is executed here, this is never executed a second time. 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.

Exporting a Function

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:

Updating app.js File

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:
New Execution Output

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:

Constructor Method

and here is the updated app.js file:
New Update to app.js File

So, this is in essence is the 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:

Output of Most Recent Change

Now, let’s 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:

Change to app.js for New File Creation

New File Execution Result

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:

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:

Code from index.js

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

app.js File Which Requires This Module

So, in our case we could say:

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

Since there isn’t a logger.js, there’s a logger directory, it’s 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:

Result of Adding index.js

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 dependencies.

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 the consumer side, use a single file. It just implies that a folder is a good way to manage those sorts 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 straightforward.

We can install a dependency using npm:

npm install underscore;

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

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

Underscore Example

Here is the output of the execution:
Output of Final Execution


In this post, we learned 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 any questions or comments. Till next time, Happy Coding!

Credit: Source link

Previous Next
Test Caption
Test Description goes like this