Nodejs Application Folder Structure
A folder is a location where we store files that are directly linked to our computer's file system. To create a Nodejs application, we need a folder structure in which we write the code and execute it to retrieve the results. This blog provides fundamental insights into the folder structure, and detailed information about particular subfolders or files will be provided quickly in subsequent blogs. The sample folder structure that I use to construct Nodejs applications is shown below.
Make a folder on your local workspace for Nodejs development.
- To begin, execute the command git init. This command generates a package.json file, which contains basic file information such as the file's name, version, description, and so on,
**For developing any application, package.json serves as a configuration file.
- Next, execute the command npm install dependency_name
to install the dependencies required for constructing a Nodejs application.
This command generates the node_modules
package and the package-lock.json
file, which contain information about all dependencies utilized in the
Application.
- I’ve developed the .gitignore file, which allows us to restrict which files and directories are uploaded to the git repository. The information in the gitignore file is as follows.
- I've developed a .env file that functions as a Global Environment, where we can initialize some of the variables' values and reuse them at the code level without re-initializing.
I declared certain global variables in the .env file, such as PORT number, Database Connection Url, and Allowed Origins.
- In the bin folder, I've included a sample
javascript file that uses mongoose.connect method to link the Nodejs
application to a Mongo Server.
- The App.js file serves as the Nodejs application's entry point. This is where we deal with routing, middleware, authentication, database connectivity, and so forth.
** All the below sub folders have Javascript files (.js) in it**
- Next, a Models
folder is established to contain the details of Schemas and Models together. Schemas are similar to Database objects
in that they define the structure of a document in a Mongoose collection. Models, in conjunction with schema,
provide as an interface for processing database calls.
- The Controllers
folder is where we write the business logic needed to construct the
application.
- Routes
folder, in which we handle various function calls to the controller files based
on the required routes. We typically use mappings such as GET, POST, PUT,
DELETE, and so on to retrieve data based on the specific controller method
call.
- The Utilities folder serves as a helper file for the application. Custom validations, errorLoggers, auxiliary classes, and so forth can be implemented here.
Normal Flow of the Nodejs Application based on the above Folder structure:-
|