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
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Building a Full-Stack Resume Screening Application With AI
  • Node.js Walkthrough: Build a Simple Event-Driven Application With Kafka
  • Node.js: Architectural Gems and Best Practices for Developers to Excel
  • How To Use the Node Docker Official Image

Trending

  • AI-Era Cybersecurity, Part 1: Mapping Glasswing, Daybreak, Lightwell and the Tools Racing to Find and Fix Bugs
  • How Kestra Unifies Enterprise Workflow Orchestration and Agentic AI
  • The Twelve-Factor Agents: Building Production-Ready LLM Applications
  • Building a Real Pipeline With senro: Monorepos, Caching, and Triggers

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  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.

By 
Vinod Surendran
·
Oct. 27, 17 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
29.3K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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

  • Building a Full-Stack Resume Screening Application With AI
  • Node.js Walkthrough: Build a Simple Event-Driven Application With Kafka
  • Node.js: Architectural Gems and Best Practices for Developers to Excel
  • How To Use the Node Docker Official Image

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

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 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook