A logical and consistent file structure makes it easy to navigate your project. Here's a common and recommended structure:
Code : Tout sélectionner
your-project/
├── src/
│ ├── config/ # Configuration files (database, etc.)
│ ├── controllers/ # Handles request logic
│ ├── middlewares/ # Functions that run before route handlers
│ ├── models/ # Data models (e.g., using Mongoose, Sequelize)
│ ├── routes/ # Defines API endpoints and links them to controllers
│ ├── services/ # Business logic (optional, but recommended for complex apps)
│ ├── utils/ # Utility functions (helpers, formatters, etc.)
│ ├── app.js # Main application setup
│ └── server.js # Entry point to start the server
├── tests/ # Unit and integration tests
├── .env # Environment variables
├── .gitignore
├── package.json
├── package-lock.json
└── README.md
Explanation:
: This directory contains all your application's source code.
: Holds configuration files for your database connections, API keys, and other settings.
: Contains controller functions. Each controller typically handles the logic for a specific resource (e.g., userController.js, productController.js). These functions receive the request and response objects and orchestrate the application logic (often involving services and models).
: Stores middleware functions. These can handle tasks like authentication, authorization, request validation, logging, and error handling. You can have global middleware or route-specific middleware.
: Defines your data structures, often using an ORM (Object-Relational Mapper) like Mongoose for MongoDB or Sequelize for SQL databases.
: Contains your route definitions. Each file in this directory typically corresponds to a specific resource or group of related endpoints (e.g., userRoutes.js, productRoutes.js). These files define the HTTP methods (GET, POST, PUT, DELETE,
block blast etc.) and the paths for your API endpoints, linking them to the appropriate controller functions.
(Optional but Recommended): For more complex applications, a services layer can encapsulate the core business logic, separating it from the request/response handling in controllers. This promotes reusability and testability.
: Contains utility functions that are used across your application.
: This file usually sets up your Express application instance, including mounting middleware, defining global settings, and connecting to databases.
: The entry point of your application. It imports app.js and starts the server, listening on a specific port.
: Contains your unit and integration tests.
: Stores environment-specific variables (API keys, database URLs, etc.).
: Specifies files and directories that Git should ignore.
and
: Manage project dependencies.