Home >Web Front-end >JS Tutorial >How to Build and Structure a Node.js MVC Application

How to Build and Structure a Node.js MVC Application

Lisa Kudrow
Lisa KudrowOriginal
2025-02-10 10:32:17764browse

How to Build and Structure a Node.js MVC Application

When building complex applications, architecture design is as important as code quality. Even if the code is well written, but lacks a good organizational structure, maintaining and scaling becomes extremely difficult as complexity increases. Therefore, the best practice is to plan the architecture before the project starts, guide the project goals and make informed choices.

Unlike frameworks such as Ruby on Rails, Node.js does not have a de facto standard framework to enforce specific architectures and code organization. This makes architecture choice relatively free when building a complete Node.js web application, but also adds challenges.

This tutorial will use the MVC architecture to build a basic note-taking application, demonstrating how to use Node.js' Hapi.js framework, SQLite database (operating through Sequelize.js), and the Pug template engine to achieve efficient development.

Core points:

  • Efficiently organize Node.js applications using MVC (Model-View-Controller) architecture to improve maintainability and scalability.
  • Initialize the project with npm and create package.json files to manage dependencies.
  • Build a server using the Hapi.js framework and manage data using SQLite database and Sequelize.js.
  • Define Node.js routes, clarify the functionality of the application, and ensure that each route is associated with the correct HTTP method and handler.
  • Define the model using Sequelize.js to ensure data integrity and provide an abstraction layer.
  • Implement the controller to process business logic, connect models and views, obtain data and determine the output format.
  • Create views using the Pug template engine to make HTTP responses more readable and structured.
  • Use the Inert plugin of Hapi.js to provide static file services and efficiently manage CSS and JavaScript files.

What is MVC?

Model-View-Controller (MVC) is probably one of the most popular application architectures. The MVC pattern was originally designed in PARC for the Smalltalk language to solve the organizational problems of graphical user interface applications. Although originally used in desktop applications, the concept has been successfully applied to web development.

Simply put, the MVC architecture includes:

  • Model: Parts of processing database or any data-related functions.
  • View (View): Everything the user sees - the page sent to the client.
  • Controller: The logic of the website, and the bridge between the model and the view. The controller calls the model to get the data, then passes the data to the view, and finally sends it to the user.

This application will allow the creation, viewing, editing and deletion of plain text notes. While the features are simple, the solid architecture will make it easy to add new features in the future.

This tutorial assumes that you have installed the latest version of Node.js on your machine. If not, please refer to the relevant tutorial for installation.

The final application code has been uploaded to the GitHub repository, and you can view the complete project structure.

Land the foundation

The first step in building any Node.js application is to create a package.json file with all dependencies and scripts. This file can be automatically generated using npm's init command:

<code class="language-bash">mkdir notes-board
cd notes-board
npm init -y</code>
Once

is finished, you will have an available package.json file.

Note: If you are not familiar with these commands, please check out our npm Getting Started Guide.

Next, install the Hapi.js framework:

<code class="language-bash">npm install @hapi/hapi@18.4.0</code>

This command will download Hapi.js and add it to the dependencies in the package.json file.

Note: We specified the v18.4.0 version of Hapi.js because it is compatible with Node 8, 10 and 12 versions. If you are using Node 12, you can choose to install the latest version (Hapi v19.1.0).

Now, create the entry file - start the web server with everything. Create a server.js file in the application directory and add the following code:

<code class="language-javascript">"use strict";

const Hapi = require("@hapi/hapi");
const Settings = require("./settings");

const init = async () => {
  const server = new Hapi.Server({ port: Settings.port });

  server.route({
    method: "GET",
    path: "/",
    handler: (request, h) => {
      return "Hello, world!";
    }
  });

  await server.start();
  console.log(`Server running at: ${server.info.uri}`);
};

process.on("unhandledRejection", err => {
  console.log(err);
  process.exit(1);
});

init();</code>

This is the basis of the application. First, we use strict mode; then, we introduce dependencies and instantiate a new server object, setting the connection port to 3000 (the port can be any number between 1023 and 65535); our first route will be Test, so the "Hello, world!" message is enough; finally, we start the server using the server.start() method.

Storage settings

Best practice is to store configuration variables in a dedicated file. This file exports a JSON object containing data, where each key is assigned an independent environment variable, but don't forget the alternate values.

In this file, we can also have different settings depending on the environment (such as development or production). For example, we can use memory instances of SQLite for development purposes, but use real SQLite database files in production environments.

Selecting settings based on the current environment is very simple. Since we also have an env variable in the file that will contain development or production, we can do the following to get the database settings:

<code class="language-javascript">const dbSettings = Settings[Settings.env].db;</code>

Therefore, when the env variable is development, dbSettings will contain the settings of the in-memory database; when the env variable is production, the path to the database file will be included.

In addition, we can add support for .env files where local environment variables can be stored for development purposes. This can be done through a Node.js package like dotenv, which will read the .env file in the root of the project and automatically add the found values ​​to the environment.

Note: If you decide to use the .env file as well, make sure to install the package using npm install dotenv and add it to .gitignore to avoid posting any sensitive information.

Our settings.jsFile is as follows:

<code class="language-javascript">// This will load our .env file and add the values to process.env,
// IMPORTANT: Omit this line if you don't want to use this functionality
require("dotenv").config({ silent: true });

module.exports = {
  port: process.env.PORT || 3000,
  env: process.env.NODE_ENV || "development",

  // Environment-dependent settings
  development: {
    db: {
      dialect: "sqlite",
      storage: ":memory:"
    }
  },
  production: {
    db: {
      dialect: "sqlite",
      storage: "db/database.sqlite"
    }
  }
};</code>

Now, we can start the application by executing the following command and navigating to http://localhost:3000 in our web browser:

<code class="language-bash">mkdir notes-board
cd notes-board
npm init -y</code>

Note: This project was tested on Node v12.15.0. If you encounter any errors, make sure you have an updated version installed.

(The following steps, due to space limitations, the following content will be briefly summarized. Please refer to the original text for specific implementation details)

Define routes: Define routes for applications in lib/routes.js files, including GET, POST, PUT, and DELETE methods to handle the creation, reading, updating and deletion of notes.

Build a model: Create a Note using Sequelize.js and SQLite to define the data structure of the notes (date, title, content, etc.). Define the model in lib/models/note.js.

Build the controller: Create the controller to handle routing requests. lib/controllers/home.jsProcessing home page, lib/controllers/note.jsProcessing CRUD operations related to notes.

Build views: Create views using the Pug template engine. lib/views/home.pugShow the list of notes, lib/views/note.pugShow individual notes details. lib/views/components/note.pugDefine the note component.

Service static files: Use the Inert plugin of Hapi.js to serve static files (JavaScript and CSS). Register the Inert plugin in server.js and add static file routes in routes.js.

Client JavaScript: Write client JavaScript code to handle display/hide modal windows, and submit forms using Ajax.

Summary

This tutorial builds a basic note-taking application based on Hapi.js and MVC architecture. While there are still many details to be refined (such as input validation, error handling, etc.), this provides a foundation for learning and building Node.js applications. You can add user authentication, more complex UI and other functions on this basis.

The above is the detailed content of How to Build and Structure a Node.js MVC Application. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn