How to create a website using Node.js and Express

Node.js Web Application

This example creates a website using Node.js to provide a logical website behavior. Using the Express.js framework, the website is implemented as a web application, with logical routing to other sections of the website.

The HTML and CSS are based on our responsive website design using CSS Grid and Flexbox. The HTML is refactored as a template, so the layout code can be reused when adding new pages.

Install Node

Node.js, also called Node, is a runtime environment for writing server-side applications in JavaScript.

Download the Node installer from the official Node.js download website. Choose the LTS (Long Term Support) version for your operating system.

Windows and macOS

Open and run the Node installer (.msi in Windows, .pkg on macOS).

On Windows, in the installation screen called Native Module Tools, check the Install automatically the necessary modules tools.

Linux

On Linux systems, you can install Node using your package manager, install the compiled binaries manually, or compile Node from source . For detailed information, see the official Node.js installation wiki.

All operating systems

When the installation is complete, open a terminal window or command prompt. Run the following command to update npm, the package manager for Node. The -g (global) switch specifies that the software is installed system-wide, not just the current Node application.

Windows

npm install -g npm

Linux and macOS

sudo npm install -g npm

Finally, use npm to globally install the express-generator application.

Windows

npm install -g express-generator

Linux and macOS

sudo npm install -g express-generator

Create a new Express application

In a terminal window or command prompt , generate a new Express.js Application. In our example, the application name is myapp, and the view engine is specified as pug.

express myapp -view=”pug”

Change directory to the new Express application.

cd myapp

In the Express application directory, use npm install to download and install the required dependencies, as indicated in the file package.json.

npm install

If security updates are available for installed dependencies, a notification is displayed.

1 low severity vulnerability found, run `npm audit fix` to fix them, or `npm audit` for details

If so, apply security updates.

npm audit fix

Install nodemon

In the Express application directory, install nodemon. The -save-dev option indicates that nodemon is a development dependency. It is not used in the application itself, but is a tool used during development.

npm install -save-dev nodemon

Add a development startup script

A development startup script provides a way to start your web application with options that help you develop the application, such as detailed error messages.

In a text editor, open the package.json file in the application directory. This JSON file specifies the dependencies used by your Node. In addition, it contains named startup scripts that start the application in different ways.

See Also:  EDirectory Blog

In package.json, locate the “scripts” entry. By default, it contains only one script (“start”).

“scripts”: { “start”: “node ./bin/www” },

Add a new line defining a devstart as follows.

Linux and macOS

“scripts”: { “start”: “node ./bin/www”, “devstart”: “DEBUG =myapp:* nodemon ./bin/www” },

Windows

“scripts”: { “start”: “node ./bin/www”, “devstart “: “SET DEBUG=myapp:*

To preview the website on a mobile device, connect your Wi-Fi to your local network and open the address in a browser.

Express.js on mobile

HTML Templates

Our Example uses CSS, JavaScript and HTML of how to create a responsive website using CSS Grid and Flexbox. The CSS and JavaScript are used verbatim. The HTML is refactored to a templating language.

Using a templating language, the layout code is written only once and is inherited by other pages.

The software that converts a template to its final format is called a template processor. In the context of HTML, a template renderer is called a rendering engine.

Express.js supports several rendering engines, including Pug.

Overview of Pug

The Pug language describes HTML documents, in a way that provides additional benefits and functionality. Pug files are rendered in HTML when requested by the user.

The Pug language syntax eliminates the need for tags to be closed or enclosed in square brackets. It also supports legacy templates, iteration, conditionals, and JavaScript evaluation.

HTML to Pug Conversion Example

Here are the first few lines of the HTML on how to create a responsive website using CSS Grid and Flexbox.

When the document is rendered, the Pug engine loads the layout.pug file. The block foo line in layout.pug is replaced with p This is the home page.

Overview of the default Express app

The default structure of the Express application is shown here, with descriptions of each file and directory.

myapp/ (Contains the entire Express application) ├─ app.js The logic Express application hub. ├─ bin/ (Contains the application’s executable scripts) │ └─ www A container that runs app.js. ├─ node_modules/ (Contains dependencies installed by npm) ├─ package-lock.json JSON manifest of installed dependencies. ├─ package.json JSON of dependencies and configuration specific to your application. ├─ public/ (Files downloaded by the user’s web browser) │ ├─ images/ (Contains client-accessible image files) │ ├─ javascripts/ (Contains client-accessible JavaScript files) │ └─ stylesheets/ (Contains Client-accessible CSS ) │ └─ style.css The CSS style sheet for the site. ├─ routes/ (Contains logic for individual site routes) │ ├─ index.js Logic for the “index” (/) route. │ └─ users.js Logic for the path “users” (/users). └─ views/ (Contains HTML templates) ├─ error.pug View displayed for error pages, such as HTML 404. ├─ index.pug View displayed for the root of the place (/). └─ layout.pug View layout template shared by all pages.

See Also:  Step 1: Get Started

The main functionality of the website is defined in app.js. Paths are named and specified in this file.

A path is a page or section of the site with a unique path in the URL, such as www.example.com /search, www.example.com/login, etc. These routes are named and associated with route logic scripts in app.js.

The route logic scripts are stored in the routes. When a user requests a route, your route logic script processes the HTTP request data and sends a response.

The views folder contains the HTML templates, called views, which are processed by the display engine (Pug).

Implementation: JavaScript, CSS, and Pug

The following code implements the Express web application .

Application file structure

myapp/ ├─ app.js Application core logic ├─ bin/ │ └─ www ├─ node_modules/ ├─ package-lock.json ├─ package.json ├─ public/ │ ├─ images/ │ ├─ javascripts/ │ │ └─ menu.js Implement menu toggle │ └─ stylesheets/ │ └─ style.css Stylesheet ├─ routes/ │ ├─ about.js Logic for route /about │ ├─ advice .js Logic for route /advice │ ├─ contact.js Logic for route /contact │ ├─ index.js Logic for path / │ ├─ recipes.js Logic for path /recipes │ ├─ tips.js Logic ica for path /tips │ └─ users.js Not used, can be removed └─ views/ ├─ about.pug View w for path /about ├─ tip.pug View for route /tip ├─ contact.pug View for route /contact ├─ error.pug ├─ index. pug View by path / ├─ layout.pug View template shared by all pages ├─ recipes.pug View by path /recipes └─ tips.pug View by path /tips blue = modified, green = new, red = not used

myapp /app.js

The core logic of the app is essentially the same as the default Express app, with additional paths defined. The “users” path is removed.

// parent dependencies var createError = require(‘http-errors’); var express = require(‘express’); var path = require(‘path’); var cookieParser = require(‘cookie-parser’); var logger = require(‘morgan’); // create route objects var indexRouter = require(‘./routes/index’);var aboutRouter = require(‘./routes/about’);var contactRouter = require(‘./routes/contact’); var tipsRouter = require(‘./routes/tips’);var recipesRouter = require(‘./routes/recipes’);var tipRouter = require(‘./routes/tips’); // the object application var application = express(); // view engine settings app.set(‘views’, path.join(__dirname, ‘views’)); app.set(‘view engine’, ‘pug’); // application settings 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’))); // tell the app to use these routesapp.use(‘/’, indexRouter);app.use(‘/about’, aboutRouter);app.use(‘/contact’, contactRouter);app.use ( ‘/tips’, tipsRouter);app.use(‘/recipes’, router recipes);app.use(‘/tips’, router tips); // catch 404 and forward to controller errors app.use(function (req, res, next) { next(createError(404)); }); // error handler app.use(function(err, req, res, next) { // set locals, only provide error in development res.locals.message = err.message; res.locals.error = req.app. get(‘env’) === ‘development’ ?err : {}; // display error page res.status(err.status || 500); res.render(‘error’); }); // expose this app to scripts that require it, ie myapp/bin/www module.exports = app;

See Also:  How To Connect Xbox One To Monitor

myapp/routes/layout.pug

The layout.pug file contains the main page layout, which is shared by all pages on the site.Contains everything needed to display a page, except the main body content (lock main body).

doctype html html head title= pagetitle meta(charset=”utf-8″) meta(name =”viewport” content=”width=device-width, initial-scale=1″) script(src=”/javascripts/menu.js”) link(rel=”stylesheet”, href=”/stylesheets/ style.css “) body #menusection #menuitems .menubutton h1.menubutton(onclick=”menuToggle(‘hide’)”)5 rows; } a:link, a:visited { /* anchor links and visited anchor links */ color: black; text-decoration: none; /* disable underlining */ } a:hover { /* when anchor link is hovered */ color: rgb(25, 25, 25); } a:active { /* when the anchor link is clicked */ color: rgb(96, 96, 96); } /* component styles */ #container { display: grid; height: 100wh; grid-template-columns: [left] 10rem auto 10rem [right]; grid-template-rows: [up] 5rem auto 5rem [down]; /* header height adjusts to its content */ grid-template-areas: “head head head” “panleft mainbody panright” “foot foot foot”; } #header { grid area: head; /* corresponds to the name in the template */ background: rgb(0, 0, 0, 0.2); /* 20% black */ screen: flex; bending direction: row; justify-content: space-between; align elements: baseline; /* site name and nav text align to baseline */ padding: 1.0rem; } #panel { /* for element id=”panel” */ display: flex; /* this element is a parent flexbox */ flex-direction: column; /* its children flex vertically */ padding: 0.5rem; background: rgb(0, 0, 0, 0.1); /* 10% black */ } #panel.left { /* for element id=”panel” and class=”left” */ grid-area: panleft; /* this element fills a grid area */ } #panel.right { grid-area: panright; } #footer { grid area: foot; flexible screen; /* this element is a parent flexbox */ flex-direction: column; /* its children flex vertically */ allow-content: center; /* horizontal center footer content */ align-items: center; /* vertical center footer content */ padding: 0.5rem; background: rgb(0, 0, 0, 0.2); } #mainbody { /* for element id=”mainbody” */ display: flex; /* this element is a parent flexbox */ flex-direction: column; /* its children flex vertically */ grid-area: mainbody; justify yourself: center; /* fixed-width main body always centered */ width: 100%; minimum width: 22.5 rem; /* the width of the main body cannot gobody space { flex-growth: 1; /* these items expand on the flex axis to fill the space */ } /* table styles (“items for sale”) */ table { border-collapse: collapse; /* table cells adjacent to pixels */ width: 100%; lower margin: 1 rem; } th { text-align: left; } tr { margin: 4rem 0 0 0; bottom border: 0.15 rem rgb solid(0, 0, 0, 0.2); /* horizontal rule */ } td, th { padding: 0.5rem; vertical alignment: top; } td.price { blank space: nowrap; /* white space in price does not wrap line */ } td.qty, th.qty { text-align: center; } span.perunit { opacity: 0.5; } /* responsive styles applied in portrait mode */ @media screen and (max-width: 45rem) { /* if viewport width

Leave a Reply

Your email address will not be published. Required fields are marked *