DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • 6 Tips to Help You Write Cleaner Code in Node.js
  • Node.js: Architectural Gems and Best Practices for Developers to Excel
  • An Introduction to Type Safety in JavaScript With Prisma
  • The Complete Tutorial on the Top 5 Ways to Query Your Relational Database in JavaScript - Part 2

Trending

  • Performance Optimization Techniques for Snowflake on AWS
  • Kubeflow: Driving Scalable and Intelligent Machine Learning Systems
  • Contextual AI Integration for Agile Product Teams
  • Scaling DevOps With NGINX Caching: Reducing Latency and Backend Load
  1. DZone
  2. Coding
  3. JavaScript
  4. Node.js – Dependency Management

Node.js – Dependency Management

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.

By 
Jawad Hasan Shani user avatar
Jawad Hasan Shani
DZone Core CORE ·
May. 10, 21 · Tutorial
Likes (15)
Comment
Save
Tweet
Share
13.1K Views

Join the DZone community and get the full member experience.

Join For Free

Introduction

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:

userRepo.js

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:

JavaScript
 




xxxxxxxxxx
1


 
1
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:

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:

JavaScript
 




xxxxxxxxxx
1


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



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

JavaScript
 




xxxxxxxxxx
1


 
1
var logger = require("./logger")



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

Summary

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!

Node.js Dependency code style application JavaScript

Published at DZone with permission of Jawad Hasan Shani. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • 6 Tips to Help You Write Cleaner Code in Node.js
  • Node.js: Architectural Gems and Best Practices for Developers to Excel
  • An Introduction to Type Safety in JavaScript With Prisma
  • The Complete Tutorial on the Top 5 Ways to Query Your Relational Database in JavaScript - Part 2

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!