How to Structure my Application in Express.js ?
Express is a minimalistic framework that is used to create web servers. It is built upon the HTTP module of node.js and provides a much easier way to manage the code related to the server.
In this article, we are going to discuss how we can structure our express application.
Create Node Project:
Step 1: As the express application is built upon NodeJS so first of all, we have to initialize a node project, write the command below in your terminal.
npm init
Step 2: Install Packages
npm install express
Step 3: Create an app.js file. In this file, we write the entire code of the server.
touch app.js
Project Structure: After all of this, our project structure will look like this.
Configure the environment variable: While writing server code several times we need some constant variable in the entire codebase, so we should set some kind of environment variable so that it can be available in all files.
This module is used to load environment variables from the .env file to the process object so that later we can easily use these variables anywhere in the codebase.
npm install dotenv
PORT=3000 // This will be available as process.env.PORT
// You can write any variable here.