Hello, dear friend, you can consult us at any time if you have any questions, add WeChat: daixieit

SENG365 Lab 1

Introduction to JavaScript, Node.js and APIs

2nd March 2023

Purpose of this Lab

This lab is split into two parts. In the first part we introduce JavaScript and Node. JavaScript is the default scripting language used in all standard web browsers (e.g., Chrome, Safari, Firefox, and Edge) and is therefore the language for implementing the majority of web applications.  Node brings the power of JavaScript to the server-side of an application. Consequently, JavaScript can be used on both the client-side and the server-side of a web application. In the second part of this lab, we begin to look at how to use Node and Express to implement APIs.

This lab looks long, but it’s mostly due to the amount of theory you need to be aware of to get started. To properly understand the concepts covered it is highly recommended you read the online resources discussed. Subsequent labs will be more practical and require less reading.

1 Overview of JavaScript

Mozilla provides a great introduction to what JavaScript is here: https://developer.mozilla.org/en-US/docs/ Web/JavaScript/Guide/Introduction. Notably the What is JavaScript? and JavaScript and Java sections.

JavaScript is a widely used cross-platform, object-oriented programming language that underpins modern web development on both the client and server side. Whilst you may not have directly interacted with or written JavaS- cript code yourself, almost every web application makes heavy use of JavaScript to provide functionality. For those interested you can visit a website in Chrome and open the dev tools (F12), navigating to the‘Sources’tab should show you many JS files though generally these have been minified1so it can be difficult to understand what’s going on.

Throughout this course we will be using TypeScript, a superset ofJavaScript (this will be discussed more in the next lab), for the majority of the exercises. Specifically we will be using the ES62 standard. If you are new to JavaScript and/or the ES6 standard then you should take some time now to familiarise yourself. There is an abundance of information available online:

https://developer.mozilla.org/en-US/docs/Web/JavaScript

https://web.dev/learn/pwa/getting-started/

https://www.w3schools.com/js/

https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/ As well as many books:

https://exploringjs.com/

https://leanpub.com/understandinges6

https://leanpub.com/es6-in-practice

2 What is Node.js?

Node.js is“an asynchronous event-driven JavaScript runtime, designed to build scalable network applications”3.

But what does that mean?

Asynchronous (Async/Await): “The async/await pattern is a syntactic feature of many programming lan- guages that allows an asynchronous, non-blocking function to be structured in a way similar to an ordinary synchronous function" providing "opportunities for the program to execute other code while waiting for a long-running, asynchronous task to complete.”4

Event driven:“In computer programming, event-driven programming is a programming paradigm in which the flow of the program is determined by events such as user actions (mouse clicks, key presses), sensor outputs, or messages from other programs/threads.”5

The Node.js runtime is built on Chrome’s V8 engine. V8 is a widely used JavaScript engine, used in Chrome (and other Chromium based browsers). V8 compiles and executes JavaScript source code, handles memory allocation for objects, and garbage collects objects it no longer needs. JavaScript is most commonly used for client-side scripting in a browser, being used to manipulate Document Object Model (DOM) objects for example. The DOM is not, however, typically provided by the JavaScript engine but instead by a browser. So V8, as a pure JavaScript engine, does not include any methods for DOM manipulation. V8 does, however, provide all the data types, operators, objects and functions specified in the ECMA standard. https://node.green/shows exactly which ES2015 (ES6) features are supported by each node version, from this we can see that versions 6.4.0 and above have the best support (though it is recommended to use current LTS version from Node.js).

There are other runtimes for JavaScript applications, often being specifically designed to work with existing Node.js projects, such as Bun6that have been created to provide specific benefits. Throughout this course we will only be discussing and using Node.js, however for those interested in web development looking at some alternatives can help give a better understanding on what these solutions provide.

2.0.1 Node Package Manager (NPM)

NPM should be thought of as two separate, though interconnected things:

•  Primarily, it is an online package repository for Node projects with well over 1 million packages and growing.

•  However, it is also a command line tool used by developers for interacting with the aforementioned repository that handles package installation, version management, dependency management and more.

2.1 Working with Node.js

The seasoned JavaScript developers amongst you may already have a preferred workflow for writing web applica- tions. For those of you who do not, then we recommend using JetBrains’WebStorm IDE. WebStorm is simple to use and is already installed on the lab machines. For any of you wanting to use WebStorm on your personal machines you can get a free education license using your university email.

2.2 Running scripts in WebStorm

Running scripts in WebStorm is easy:

1. Open WebStorm.

2. Select Create New Project.

3. Create an empty project (make sure to rename your project first). The IDE will open your project directory.

4.  Right click on your project directory and select: New > JavaScript File.

5. When prompted for a filename, call it test.js.

6. Your new file will open, add the following code from Listing 1.

1   console .log('Hello! ' )

Listing 1: A simple console.log JS script

7.  Run your script by right-clicking and clicking Run ‘test.js’ or using the shortcut SHIFT+F10. Alternat- ively: you can run your scripts by opening your terminal (View > Tool Windows> Terminal) and entering the command nodetest .js.

For more information refer to WebStorm’s online documentation7.

Note: You may need to set up WebStorm to validate ES2015 (ES6) code. To do this go to File > Settings > Languages & Frameworks > JavaScript and set the JavaScript Language Version to ECMAScript6.

2.3 Download and Installation (If using a personal computer)

1. Download the recommended version of Node from https://nodejs.org/en/

2. Run the downloaded file and navigate through the wizard.

3. Confirm the installation by opening your terminal and typing node. You should be presented with the node prompt >.

4. Confirm that node has been installed correctly by moving onto Exercise 1.

2.4 Exercise 1: Hello World

1. Create a file named exercise1.js.

2. Open the file and insert the code from Listing 2.

1 /* Hello, World ! program in node .js */

2 console .log('Hello , World ! ' );

Listing 2: A simple console.log JS script

3. Open your terminal, navigate to the directory where your file is and run the command nodeexercise1 .js.

4.  If node was successfully installed,“Hello World!”should be printed to the console.

2.5 Exercise 2: Write a Web Server

In Node, we load modules into other modules using the require directive, similar to how Python uses import.

1. Create a new file called exercise2.js.

2.  Use the require directive to import the http module into a variable for later use.

1 const http = require('http ' );

Listing 3: Importing http

Note: You may see WebStorm put a yellow underline on the require function and on hover say“Unresolved function or method require()”. This means you need to enable Node.js coding assistance. To do this, go to: File > Settings > Languages & Frameworks > Node.js and NPM and tick the“Coding assistance from Node.js” box.

3.  Now use the http module’s createServer function to create a new server. The example code in Listing 4 ignores the content of any request given and instead will just return a 200 OK response with the text“Hello World”.

1 http .createServer((request, response)  =>  {

2 // Send the HTTP header

3 // HTTP Status: 200 (OK)

4 // Content Type : text/plain

5 response .writeHead(200,  {'Content-Type' : 'text/plain'});

6 // Send the response body as "Hello World"

7 response .end('Hello World\n');

8 }) .listen(8081);

9 console .log('Server running at http ://127 .0 .0 .1:8081/');

Listing 4: Basic http server with createServer

The documentation for createServer can be found here8.

4. Open your terminal and run nodeexercise2 .js.

5. Open your browser and navigate to http://localhost:8081/.

2.6 Exercise 3: Handling URL Parameters

Next we want to be able to retrieve URL parameters so that we can use them in our application. Wikipedia provides an explanation of what URL parameters are and their syntax9.

1. Make a copy of exercise2.js and call it exercise3.js.

2.  Use the require directive to import the URL class from the url module. This module allows us to easily parse URLS.

1 const http = require('http ' );

2 const URL = require('url ' ) .URL;

Listing 5: Http and url imports

3.  Next, edit the contents of your createServer function. Now whenever we receive a request, we will parse the URL to retrieve its search Params. We will then return a 200 HTTP response with the parameters we found in the response body. Essentially we are "parroting" the request back to the user.

1    http .createServer((request,  response)  =>  {

2        &nb