Advanced Application Structure

A real world Node.js application will most likely consist of multiple pieces. An API application for example will include at least a HTTP server and a database layer. These two components are equally important - two features - and thus should be treated as two unrelated standalone sub applications.

This chapter explains how to properly structure more complex Node.js application which consists of multiple components.

In the previous chapter Simple API Server, we built a simple HTTP server. Let's continue where we left off.

The Plan

We need to split the application features into standalone components and then expose them through application's public interface.

Components are unaware of a global application context, application configuration or application state. A component must be reusable and can be used multiple times inside or outside the project. This means that we need to instantiate and configure it before any interaction take place.

The application will have a single entry point (as before) which will automatically instantiate and configure application components when the application instance is created.

Refactoring

Moving the HTTP server files into a new sub folders called server. The application structure should look similar the the one below.

src
└─ server
   └─ routes
      └─ users.js
   └─ index.js
   └─ router.js
└─ scripts
   └─ start.js
└─ config.js
└─ index.js
.gitignore
package.json
README.md

Create a new file ./src/index.js and expose the server feature.

exports.Server = require('./server').Server;

results matching ""

    No results matching ""