0% found this document useful (0 votes)
4 views

Lab03 - Introduction to NodeJS

This document outlines Lab 3 for an Introduction to Node.js course, detailing learning objectives, installation instructions for Node.js and Visual Studio Code, and fundamental concepts such as modules and the Node Package Manager (NPM). It includes lab tasks focused on creating a simple Node.js application, routing, using template engines, and handling forms. Additionally, it specifies submission requirements and references for further learning.

Uploaded by

ascoldasice10
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Lab03 - Introduction to NodeJS

This document outlines Lab 3 for an Introduction to Node.js course, detailing learning objectives, installation instructions for Node.js and Visual Studio Code, and fundamental concepts such as modules and the Node Package Manager (NPM). It includes lab tasks focused on creating a simple Node.js application, routing, using template engines, and handling forms. Additionally, it specifies submission requirements and references for further learning.

Uploaded by

ascoldasice10
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Lab 3. Introduction to Node.

js
UNIVERSITY OF INFORMATION TECHNOLOGY

1
3. INTRODUCTION TO NODE.JS
Website Design and Development

A. OVERVIEW
1. Learning Objective
In this lab, students will be:

▪ Understanding Node.js fundamentals: the role of Node.js in server-side


development, the concept of modules.

▪ I am setting up the development environment, including installing


Node.js and npm on the local machine. Set up Visual Studio Code as a
code editor. Configure some extensions for Node.js development.

▪ We will work with the npm (Node Package Manager) to manage the third
libraries and external packages for web applications.

▪ Create a simple Node.js application and the concept of routing,


middleware, template engines, and handing forms.

2. Tools and environments


a. Installing NodeJS

Download and install the suitable NodeJS version from https://nodejs.org/. Follow
the installation instructions for your operating system. You are recommended to

University of Information Technology WEBSITE DESIGN AND DEVELOPMENT LABS – v09/2024


[email protected]
Lab 3. Introduction to Node.js

2
choose the LTS (Long-Term Support) to have support with updates, bug fixes,
and security patches for a more extended period.

Figure 1: Download the installer

Figure 2: Open the installer and follow the instructions to install Node.js

b. Installing Visual Studio Code and extensions

The Visual Studio Code is recommended for developing the Node.js application.
It's a free coding editor that helps you start coding quickly. You need to browse to
https://code.visualstudio.com/ and choose the appropriate installer for your
machine's platform to download and install.

University of Information Technology WEBSITE DESIGN AND DEVELOPMENT LABS – v09/2024


[email protected]
Lab 3. Introduction to Node.js

3
Figure 3: Visual Code Studio

Then, in VS Code, go to Extensions (Ctrl/Cmd + Shift + X), search for "nodejs”


extensions, and install them. This step is not required but provides essential tools
for NodeJS development.

3. Background knowledge
a. Primitive Types

Node.js includes the following primitive types:

▪ String
▪ Number
▪ Boolean
▪ Undefined
▪ Null
▪ RegExp
Everything else is an object in Node.js.

b. Function

Functions are first-class citizens in Node’s JavaScript, similar to the browser's


JavaScript. A function can also have attributes and properties. It can be treated
like a class in JavaScript.

function Display(x) {
console.log(x);
}

// Display(100);

University of Information Technology WEBSITE DESIGN AND DEVELOPMENT LABS – v09/2024


[email protected]
Lab 3. Introduction to Node.js

4
c. Process object

Each Node.js script runs in a process. It includes a process object to get all the
information about the current process of the Node.js application.

> process.execPath
'C:\\Program Files\\nodejs\\node.exe'

> process.pid
2156

> process.cwd()
'D:\\App\\'

d. Node.js module

Module in Node.js is a simple or complex functionality organized in single or


multiple JavaScript files that can be reused throughout the Node.js application.

Each module in Node.js has its context, so it cannot interfere with other modules
or pollute the global scope. Also, each module can be placed in a separate .js file
under a separate folder.

Node.js core modules are compiled into Node.js binary distribution and load
automatically when the Node.js process starts. However, it would be best to
import the core module to use in your application.

Module Description
http Includes classes, methods, and events to create Node.js http
server.
url Includes methods for URL resolution and parsing.
querystring Includes methods to deal with query string.
path Includes methods to deal with file paths.
fs Includes classes, methods, and events to work with file I/O.
util Includes utility functions useful for programmers.
To use Node.js core or NPM modules, you first need to import it:

var module = require('module_name')

//e.g.,
// var http = require('http')

University of Information Technology WEBSITE DESIGN AND DEVELOPMENT LABS – v09/2024


[email protected]
Lab 3. Introduction to Node.js

5
The required function will return an object, function, property, or any other
JavaScript type, depending on what the specified module returns.

e. NPM – Node Package Manager

Node Package Manager (NPM) is a command line tool that installs, updates, or
removes Node.js packages in your application. It is also an online repository for
open-source Node.js packages.

The official website is https://www.npmjs.com (you can find the necessary


packages here).

NPM is included by default when installing Node.js. You can check the running
version of NPM by using the npm -v command in the terminal. If you have an
older version of NPM, then you can update it to the latest version with the
command npm install npm -g

Some common commands with NPM:

// Install package
npm install <package name>

// Update package
npm update <package name>

// Remove package
npm uninstall <package name>

University of Information Technology WEBSITE DESIGN AND DEVELOPMENT LABS – v09/2024


[email protected]
Lab 3. Introduction to Node.js

6
B. LAB TASKS
You should do the following tasks in sequence. If you already know about Node.js
development, you can skip the first four tasks and complete the final task for this
lab.

1. Create first application


Create a new folder for your application, e.g., D:\app
Open the created folder with Visual Studio Code
Open the VS Code Terminal: View →Terminal (you should select the
Command Prompt as Terminal)
Install the express
Install the Express Generator by running the following commands from a
terminal:
npm install -g express-generator

The -g switch installs the Express Generator globally on your machine so


that you can run it from anywhere.
Create a new application:
cd D:\app
express --view ejs

If you can't use the express ('express' is not recognized as an


internal or external command, operable program, or batch file),
Follow the instructions about editing the environment variables at
https://www.c-sharpcorner.com/article/how-to-addedit-path-
environment-variable-in-windows-11/ , append the item %APPDATA%\npm
to PATH variable .
Install the required packages:
cd D:\app
npm install

Start the application


cd D:\app
npm start

Open a web browser, access http://localhost:3000

University of Information Technology WEBSITE DESIGN AND DEVELOPMENT LABS – v09/2024


[email protected]
Lab 3. Introduction to Node.js

7
Figure 4: The first web application

1. Follow the instructions and create a new web application.


2. Take a look at the application folder. What folders and files were created?
Briefly describe the role and purpose of these files and folders.

2. Routing
Routing refers to determining how an application responds to a client request to
a particular endpoint, a URI (or path), and a specific HTTP request method (GET,
POST, and so on).

Each route can have one or more handler functions executed when the route is
matched.

Route definition takes the following structure:

app.METHOD(PATH, HANDLER)

Where:

▪ app is an instance of express


▪ METHOD is an HTTP request method in lowercase (get, post, post, put,
delete, etc.)
▪ PATH is a path on the server.
▪ HANDLER is the function executed when the route is matched.
From task 1, when bootstrapping a new application with express-generator, the
routing for the application was separated into files inside the routes folder. You
will alter the routes/index.js file to append new routes.

var express = require('express');


var router = express.Router();

router.get('/hello', function(req, res, next) {


res.send('Hi');

University of Information Technology WEBSITE DESIGN AND DEVELOPMENT LABS – v09/2024


[email protected]
Lab 3. Introduction to Node.js

8
});

module.exports = router;

Some documentation related to routing:

▪ Basic routing: https://expressjs.com/en/starter/basic-routing.html

▪ Express routing: https://expressjs.com/en/guide/routing.html

3. Template engines
A template engine enables you to use static template files in your application. At
runtime, the template engine replaces variables in a template file with actual
values, transforms the template into an HTML file, and then sent to the client.
This approach makes it easier to design an HTML page.

Some popular template engines that work with Express are Pug, Mustache, and
EJS. The Express application generator uses Jade as its default but supports several
others. The example in task 1 has chosen EJS as a template engine.

The template files should be placed in the views folder. With express-generator,
views/index.ejs file was created by default. Look at this file and practice on it.

Below is an example of using a template engine:

routes/index.js
1 /* GET home page. */
2 router.get('/', function(req, res, next) {
3 res.render('index', { title: 'Express' });
4 });
5

The function res.render() will render the content from the template:

▪ First argument: the name of the template file (without file extension)

▪ The second argument: options/data for template

views/index.ejs
1 <!DOCTYPE html>
2 <html>
3 <head>
4 <title><%= title %></title>
5 <link rel='stylesheet' href='/stylesheets/style.css' />

University of Information Technology WEBSITE DESIGN AND DEVELOPMENT LABS – v09/2024


[email protected]
Lab 3. Introduction to Node.js

9
6 </head>
7 <body>
8 <h1><%= title %></h1>
9 <p>Welcome to <%= title %></p>
10 </body>
11 </html>
12

4. Form handling
Forms can be submitted using the GET method or the POST method.

GET method forms are recommended for simple forms like a search query or
specifying a user's id. The form submission details are passed in the request URL
and can be seen in the browser address bar.

POST method forms are recommended for forms with sensitive data, such as user
login, and forms that send data to the backend, such as submitting an article. The
POST method is the only way to upload files.

a. Handling GET form

Below are two ways of sending data to Express using the GET method. Both these
methods work right out of the box, and you don't need to install any packages to
make them work.

▪ GET parameters: the standard for GET form submissions across all browsers
and backend systems. It consists of a key and a value in the URL string,
specified after a ?. More than a key-value pair can be defined by using & as
a demarcator.

The submitted data is accessible in the req.query object.

Giving the URL:


http://localhost:5000/books?category=biographies&type=paperback

You can access the GET parameters in Express as follows:

1 router.get('/books', function(req, res, next) {


2 console.log('Category: ' + req.query['category']);
3 console.log('Type: ' + req.query['type']); })
4 }

▪ Using name placeholders:

University of Information Technology WEBSITE DESIGN AND DEVELOPMENT LABS – v09/2024


[email protected]
Lab 3. Introduction to Node.js

10
5. Greeting application

Figure 5: Information supply form

Figure 6: The result page for information providing

University of Information Technology WEBSITE DESIGN AND DEVELOPMENT LABS – v09/2024


[email protected]
Lab 3. Introduction to Node.js

11
C. REQUIREMENTS AND SUBMISSION
You must complete all tasks in section B (Lab tasks). Advanced tasks are optional,
and you could get bonus points for completing those tasks. This lab is designed
for individuals. You have seven days to clear all tasks.

Your submission must meet the following requirements:

▪ Take a screenshot of your application/website.

▪ If the submission contains more than one file, you must place all
files/folders inside a folder whose name pattern is "StudentID-Name.”
Then, archive this folder in the zip format.

Your submissions must be your own. You are free to discuss with other classmates
to find the solution. However, copying is prohibited, even if only a part of your
report. Both reports of the owner and the copier will be rejected. Please remember
to cite any source of the material (website, book, etc.) that influences your solution.

D. REFERENCES
1. W3Scholl HTML Tutorial: https://www.w3schools.com/html/
2. HTML elements reference: https://developer.mozilla.org/en-US/docs/Web/HTML/Element
3. HTML Tutorial: https://www.geeksforgeeks.org/html
4. CSS: https://www.w3schools.com/css/default.asp

University of Information Technology WEBSITE DESIGN AND DEVELOPMENT LABS – v09/2024


[email protected]

You might also like