Unlike Django and Rails which have a defined way of doing things, file structure, etc., Express does not follow a defined way. This means you can structure the application the way you like. But as your application grows in size, it is very difficult to maintain it if it doesn't have a well-defined structure. In this chapter, we will look at the generally used directory structures and separation of concerns to build our applications.
First, we will discuss the best practices for creating node and Express applications.
Always begin a node project using npm init.
Always install dependencies with a --save or --save-dev. This will ensure that if you move to a different platform, you can just run npm install to install all dependencies.
Stick with lowercase file names and camelCase variables. If you look at any npm module, its named in lowercase and separated with dashes. Whenever you require these modules, use camelCase.
Don’t push node_modules to your repositories. Instead npm installs everything on development machines.
Use a config file to store variables
Group and isolate routes to their own file. For example, take the CRUD operations in the movies example we saw in the REST API page.
Let us now discuss the Express’ Directory Structure.
Express does not have a community defined structure for creating applications. The following is a majorly used project structure for a website.
There are other approaches to build websites with Express as well. You can build a website using the MVC design pattern. For more information, you can visit the following links.
APIs are simpler to design; they don't need a public or a views directory. Use the following structure to build APIs −
test-project/ node_modules/ config/ db.js //Database connection and configuration credentials.js //Passwords/API keys for external services used by your app models/ //For mongoose schemas users.js things.js routes/ //All routes for different entities in different files users.js things.js app.js routes.js //Require all routes in this and then require this file in app.js package.json
You can also use a yeoman generator to get a similar structure.