Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Build Your Node.js Application in a Modular Way

DZone's Guide to

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.

· Web Dev Zone
Free Resource

Tips, tricks and tools for creating your own data-driven app, brought to you in partnership with Qlik.

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.

Explore data-driven apps with less coding and query writing, brought to you in partnership with Qlik.

Topics:
npm ,web dev ,node.js ,javascript

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

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}