Create web interface for NTP server – apps.js (Part 2)

Posted by:

|

On:

|

Let’s understand the file structures first.

Files and directories are created when node.js is installed. Each of these directories serves a distinct purpose in organizing the various components of a web application, facilitating maintainability and clarity in your project’s structure. Here’s a breakdown of the types of files typically found in the specified directories of a Node.js application:

1. apps/public/javascripts/

This directory usually contains JavaScript files that are used in the client-side of the application. Common files might include:

  • Custom Scripts: JavaScript files that implement functionality for the frontend, such as form validation, AJAX requests, or interactive features.
  • Libraries/Frameworks: Third-party libraries (e.g., jQuery, Vue.js) that are included for use in the client-side code.
  • Module Files: If using modular JavaScript (e.g., ES6 modules), you might find files structured for import/export.

2. apps/public/images/

This directory holds image files that are used in the application. Common file types include:

  • JPEG/PNG/GIF: Images for the user interface, such as logos, icons, and background images.
  • SVG: Scalable vector graphics for icons and illustrations.
  • Thumbnails: Smaller versions of images for display in galleries or lists.

3. apps/public/stylesheets/

This directory contains CSS files that define the styles for the application. Common files might include:

  • Main Stylesheet: A primary CSS file that applies styles across the application (e.g., style.css).
  • Component Styles: CSS files for specific components or sections of the application (e.g., header.cssfooter.css).
  • Frameworks: Stylesheets from CSS frameworks like Bootstrap or Tailwind CSS, if used.
  • Preprocessor Files: If using preprocessors like SASS or LESS, you might find .scss or .less files that will be compiled into CSS.

4. apps/routes/

This directory typically contains route definitions for the server-side of the application. Common files might include:

  • Route Handlers: JavaScript files that define endpoints for the application (e.g., userRoutes.jsproductRoutes.js), handling requests and responses.
  • Middleware: Files that define middleware functions that can be used in routes (e.g., for authentication or logging).
  • API Endpoints: If the application has an API, this directory may include files specifically for API routes..

5. app.js

In a Node.js application, app.js typically serves as the MAIN ENTRY POINT for the application. Here are the key functions and roles of app.js:

a) Application Setup:
app.js is where you initialize your Node.js application. This includes setting up required modules (like Express) and configuring middleware.

b) Routing:
It defines the routes for handling incoming requests. You can specify how the application should respond to different HTTP methods and endpoints.

c) Middleware Configuration:
You can configure middleware functions to process requests. This includes body parsers, logging, authentication, and error handling.

d) Database Connection:
If your application interacts with a database, app.js can be used to establish the database connection.

e) Server Initialization:
The file typically contains code to start the server, defining the port on which the application will listen for incoming requests.

f) Configuration Management:
It can hold configuration settings for the application, such as environment variables, port numbers, and API keys.

g) Error Handling:
You can define global error handling middleware to catch and respond to errors that occur in your application.

Detailed Breakdown of app.js

  1. Module Imports:
var createError = require('http-errors');
var express = require('express');
const session = require('express-session');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
  • http-errors: A utility for creating HTTP error objects. It simplifies error handling by providing standardized error responses.
  • express: The core framework for building web applications in Node.js.
  • session: module provides middleware for managing user sessions, allowing you to store and retrieve session data across multiple requests.
  • path: A built-in Node.js module used for handling file and directory paths.
  • cookie-parser: Middleware to parse cookies from incoming requests.
  • morgan: A middleware for logging HTTP requests to the console or a file.

Need to run the following command to install the express-session package

npm install express-session

Session will be used in JavaScript (js) file to store and retrieve session data.

2. Route Imports:

var indexRouter = require('./routes/index');
var dashboardRouter = require('./routes/dashboard');

These lines import route definitions from separate files. Each router handles specific paths, separating concerns for better organization.

3. Express Application Instance

var app = express();

An instance of an Express application is created, which will be used to define routes, middleware, and settings.

4. View Engine Setup

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
  • Views Directory: Sets the directory where view templates are located (in this case, views).
  • View Engine: Configures the application to use Jade (now known as Pug) as the templating engine for rendering HTML views.

5. Middleware Setup

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
  secret: 'your-secret-key',
  resave: false,
  saveUninitialized: true
}));
  • logger(‘dev’): Logs HTTP requests in a concise format. Useful for development.
  • express.json(): Middleware to parse JSON bodies of incoming requests.
  • express.urlencoded({ extended: false }): Middleware to parse URL-encoded bodies (e.g., from forms). The extended option determines whether to use the querystring library or the qs library for parsing.
  • cookieParser(): Parses cookies from the request and populates req.cookies.
  • express.static(): Serves static files from the public directory, making assets like images, CSS, and JavaScript accessible.
  • secret: This is a string used to sign the session ID cookie. It is crucial for ensuring the integrity of the session data. If the secret changes, existing sessions will be invalidated.
  • resave: determines whether to save the session back to the session store, even if it was never modified during the request. Setting resave to false can help reduce unnecessary writes to the session store.
  • saveUninitialized: controls whether to save a new session that is uninitialized (i.e., new but not modified) to the session store.  Setting it to false can help prevent the creation of empty sessions and is generally better for performance.

6. Routing

app.use('/', indexRouter);
app.use('/dashboard', dashboardRouter);
  • indexRouter: Handles requests to the root URL (/).
  • usersRouter: Handles requests to the /users URL. This modular approach helps keep the code organized.

7. 404 Error Handling

app.use(function(req, res, next) {
  next(createError(404));
});

This middleware catches requests that do not match any defined routes and creates a 404 error.

8. Error Handling Middleware

app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});
  • This middleware handles errors that occur during request processing.
  • It sets res.locals properties to pass error information to the view, displaying detailed error information in development mode.
  • It sets the HTTP status code and renders an error page using the configured view engine.

9. Exporting the Application

module.exports = app;

This line exports the Express application instance, allowing it to be imported and used in other files (e.g., in a server file that starts the application).

Important note to remember:

From the code

app.use('/', indexRouter);
var indexRouter = require('./routes/index');

It means when there is a URL request from HTML files like ‘/‘ , express will call the route indexRouter to handle. indexRouter will then check route definitions and run the code of JavaScript file “index.js” in the directory ./routes.

Next, we will create a new index.js file. Let’s plan to do that on another day (Part 3).

Posted by

in