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
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
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

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • Node.js: Architectural Gems and Best Practices for Developers to Excel
  • How To Use the Node Docker Official Image
  • Building the World's Most Resilient To-Do List Application With Node.js, K8s, and Distributed SQL
  • 7 Ways of Containerizing Your Node.js Application

Trending

  • Top 7 Best Practices DevSecOps Team Must Implement in the CI/CD Process
  • Exploring String Reversal Algorithms: Techniques for Reversing Text Efficiently
  • Multi-Tenancy With Keycloak, Angular, and SpringBoot
  • Smart Contract Language Comparison: Solidity vs. Cadence vs. Move
  1. DZone
  2. Coding
  3. JavaScript
  4. Build Your Node.js Application in a Modular Way

Build Your Node.js Application in a Modular Way

A developer takes us through the process of building an application using Node.js, and how he prefers to organize his files and code.

Vinod Surendran user avatar by
Vinod Surendran
·
Oct. 27, 17 · Tutorial
Like (9)
Save
Tweet
Share
28.27K Views

Join the DZone community and get the full member experience.

Join For Free

nowadays, almost all web services or integrations are done on top of node.js run-time. node.js is a flexible platform with a lot of community support. it is even possible to create documents like xlsx, docx, or pdf directly from node.js. all major cloud platforms use node.js as their level 1 language.

modularity

node.js, by design, achieves modularity by using the node_modules structure. all the required modules are stored in a node_modules directory and we can invoke the modules anywhere in our code.

but are we using this modularity in our application code. most of the applications i see contain a lib folder, in which we store all js files. these js files are imported into the required areas using relative paths.

const db = require("../db/")

const logging = require ("../../logging") 

the main problem with this kind of approach is that when we change the path of a service file the path to the db should change. also, the format is not readable. we will be confused with the file's authenticity.

the solution

a much better approach is to design our application as modules, such as db, logging, error, etc. let's say your application name is cms, then it is much easier to represent the module using scope.

require("@cms/db")

you can develop the modules separately and publish them to any npm server (public/private) and use it as like any other module.

if your application needs the logging module:

npm install --save @cms/logging

if you don't want to split your application into bits and pieces, there is another approach.

a better way

keep the modules that you want inside a separate folder. let's say "@cms." use a separate folder for each module and let the modules have a separate package.json. this way it will become a valid node module.

the package.json for the modules will look like this

{
  "name": "@cms/db",
  "version": "1.0.1",
  "description": "db module for cms application",
  "main": "index.js",
  "dependencies":{
"mysql" : "latest"
  }
}

once the modules are ready now its time to do some scripting. add the install.js in the "scripts" folder.

let fs = require('fs')

console.log('creating symlinks ...')
if (fs.existssync('node_modules/@cms')) {
    console.log('link exists already ')
} else {
    let source = '../@cms'
    console.log(`creating link for ${source}`)
    fs.symlinksync(source, 'node_modules/@cms', 'junction')
    console.log('done')
}

add this script to your main package.json.

{
  "name": "cmsapplication",
  "version": "1.0.1",
  "description": "sample cms application",
  "main": "index.js",
  "scripts": {
    "install": "node scripts/install.js",
    "start": "node index.js"
  },
  "dependencies":{
"express" : "latest"
  }
}

the script will be executed every time you do npm install. so once all other node modules are defined and the dependencies are installed, it will create a link from the @cms folder outside to the @cms folder inside node_modules. so any changes you make to the outer @cms folder will be reflected to the folder inside node_modules.

you can see that the symlinks are installed for @cms. this is not a shortcut file rather than hard links created using "ln" in linux.

inside @cms you can see our modules which are defined in the outer @cms folder.

this way you can achieve modularity. the "@cms" folder is part of your source code. you can then import the required modules in the normal way.

const {logger} = require("@cms/logging")

logger.info("welcome to cms application")

when you want your application to execute, run " npm install " followed by "npm start ."

this approach helps me in making the application more modular and extensible. let me know your thoughts on this.

application Node.js Build (game engine)

Published at DZone with permission of Vinod Surendran. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Node.js: Architectural Gems and Best Practices for Developers to Excel
  • How To Use the Node Docker Official Image
  • Building the World's Most Resilient To-Do List Application With Node.js, K8s, and Distributed SQL
  • 7 Ways of Containerizing Your Node.js Application

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • 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: