Node-Express basic Project Setup with folder Structure for beginners

systembugbd

Shaheb Ali

Posted on December 8, 2021

Node-Express basic Project Setup with folder Structure for beginners

Clean Code Architecture

Over the last several years we’ve seen a whole range of ideas regarding the architecture of systems. These include:

Hexagonal Architecture (a.k.a. Ports and Adapters) by Alistair Cockburn and adopted by Steve Freeman, and Nat Pryce in their wonderful book Growing Object Oriented Software
Onion Architecture by Jeffrey Palermo
Screaming Architecture from a blog of mine last year
DCI from James Coplien, and Trygve Reenskaug.
BCE by Ivar Jacobson from his book Object Oriented Software Engineering: A Use-Case Driven Approach

Don't get panic to see above architectural article, all above only for your reference, if you wish to read and gather knowledge you can through the link.
See below article to create a express server and project setup step by step.

Basic setup step by step

Open cmd and go to your desired folder now write -
mkdir cleancodeStructure
cd cleancodeStructure
npm init -y to initiate the package.json file into your project you will see in sidebar- package.json
now install few package into your project to make it trackable and maintainable and workable-
npm i express cros morgan dotenv
dependencies

also install nodemon to keep your server ups and running once start

npm i -D nodemon -D as a devDependencies
devDependencies

now create server.js server.js

in the same level of package.json package.json

import some necessary file to server.js like below
import some necessary file to server.js

and write few lines of code to make a nodejs server like below Please give online line break-
server.js
now come to the next level of app and router section which you already included in server.js but not yet created.

create app folder in the package.json level and create *app.js * to create express app for your project
App Folder with app.js to work with app level codebase

App Folder with app.js to work with app level codebase

now import express into the app.js file with getAppHealthCheckerController, don't worry will talk about getAppHealthCheckerController later.

import express into the app.js

now come to below line and create a express app like below
express app

then define a route for app health called /health route in the app.js like below and export express app -
the app health route

now come to the router controller part, I mention above that, I will discuss about getAppHealthCheckerController latter, now time to discuss in a short about app health route and Controller.

/health route
Most of the server for backend API they checked one route that must be exists. do you know what is that? ok, I am telling you this is called /health route. digital ocean one of the server service provider look first for /health route. if API has health route they think that the API server health is good. generally this route expect status code 200 in response back.

now create controller folder in the package.json level or first level and app.js controller inside the controller folder like below controller folder

and code inside app.js like below-

app.js

now config your package.json file script like below -
script dev

now you are ready to check your /health route from browser.
go to terminal of of your vscode and type npm run dev and hit http://localhost:4444/health

its time to Bloom

http://localhost:4444/health

Welcome you made an express app with the health route; you are almost done to go a good way to write your code in a good structure.

now create a routes folder with router.js file like below example.
routes folder with router.js

and create some route like below
some route

then go to Controller folder to create some controller which you attached with the above new route (getHomeController, getBlogController, getBlogByIdController), in router.js file.

at first create home.js in controller folder and write some demo code for home route like below.

home.js
Secondly create blog.js in controller folder and write some code for blog route like below.

define a blogData variable to write demo blog data for example -
blogData

now define a controller function getBlogController like below to make the /blog route workable and to see the blog API and paginate the Blog API;

getBlogController

I keep the all the code in this controller to make it simple, you can separate with the middleware.

now hit http://localhost:4444/blog

Blog

you can paginate the Blog API like below http://localhost:4444/blog?page=2&limit=1
Blog API

now create another route controller to get the blog by id. Its very simple to get specific blog data no matter where it is coming it may come from mongodb or javascript object or JSON data or some where else, see below how to get data from javascript object by controller function in blog.js

blog.js

and export both controller function,

you can create index.js file to export your all controller function from the controller folder together which will
help you a lot to minify your code base and keep your code clean.

index.js

index.js

when you call the specific controller you just need to call the const { yourController } = require('../controller'); and extract the specific controller to use.

Wow

we are almost done, now see some middleware and wrap up for now...

middleware

Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. The next middleware function is commonly denoted by a variable named next.

Middleware functions can perform the following tasks:

  • Execute any code.
  • Make changes to the request and the response objects.
  • End the request-response cycle.
  • Call the next middleware function in the stack.

If the current middleware function does not end the request-response cycle, it must call next() to pass control to the next middleware function. Otherwise, the request will be left hanging.

how to create a middleware and how to use see below example and folder structure

now create a folder called middleware like below and create a demo middleware for testing purpose.
middleware
write some code like below to demo.js middleware
demo.js

import and use to server.js for all route

Server.js

See middleware is working--
middleware
for more details click here to visit express.js

Error handler

you can create error folder in first level and create your own custom error handler, like below

error handler
errorHandler.js code sample looks like -

error handler

use it in server.js like below by using app.use()

server.js
if error occur error message will show of the unexpected route
error message

you are almost done with setup

Now you create all other folder for your convenient, it may be anything which one is required for your project, like below-
log, service, public, utils, db, models etc as per your needs

Folder structure

thank you

You can see a video more about NODE and Expressjs server and Paginated API creation-

You can learn docker from this video

that's all about folder Structure and node express server creation with error handling and middleware


Above all I am human being, I have lots of mistake and lack of knowledge. So if i made any mistake and provide any misinformation, please correct me and pardon me.

kudhahafez

💖 💪 🙅 🚩
systembugbd
Shaheb Ali

Posted on December 8, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related