Share
Explore

CSD3103: Practices of Node.js NPM Application Development with Visual Studio Code

Objective: Familiarize you with the basics of Node.js development using NPM (npmjs.com) and Visual Studio Code, and execute JavaScript coding drills escalating from simple scripts to TypeScript objects.
megaphone

Is "npm" an acronym for "Node Package Manager"?

npm is not an acronym
Contrary to popular belief, npm is not in fact an acronym for "Node Package Manager"; It is a recursive bacronymic abbreviation for "npm is not an acronym" (if the project was named "ninaa", then it would be an acronym). The precursor to npm was actually a bash utility named "pm", which was the shortform name of "pkgmakeinst" - a bash function that installed various things on various platforms. If npm were to ever have been considered an acronym, it would be as "node pm" or, potentially "new pm".

Setup and Introduction

Installation: Ensure Visual Studio Code is installed along with the Node.js runtime. Install Node.js from and Visual Studio Code from .
Visual Studio Code Configuration:
Install the following extensions: ESLint, Prettier, and npm. And Live Server.
Configure your environment for Node.js by setting up launch.json for debugging.
Create Your First Node.js Project:
Open Visual Studio Code, create a new folder named NodeJsBasics, and open it.
Open a new terminal in Visual Studio Code and run npm init -y to create a package.json file.
Install Express.js as an example of a Node.js framework: npm install express.
Introduction to NPM:
Discuss the purpose of NPM and its role in managing packages and dependencies.
Explore package.json and its significance in a Node.js project.

JavaScript Coding Drills

Drill #1: Hello World
Create a file hello.js and write a simple script to print "Hello, World!" to the console.

Drill #2: Basic Variables
Use var,let and const to declare variables. Create a script that calculates the area of a rectangle and prints it.
image.png
Drill #3: Functions and Scoping
Write a JavaScript function that takes two numbers and returns their sum. Demonstrate function scoping.
megaphone

Here are the JavaScript programs for the first three coding drills :

Drill #1: Hello World

Create a file named hello.js and add the following JavaScript code:
console.log("Hello, World!");

To run this script, use the command line and navigate to the directory containing your hello.js file, then execute:
node hello.js

This will print "Hello, World!" to the console.

Drill #2: Basic Variables

Create a file named rectangleArea.js and add the following JavaScript code:
// Declare dimensions of the rectangle using let
let length = 5; // length of the rectangle
let width = 3; // width of the rectangle

// Calculate area using const
const area = length * width;

// Print the area to the console
console.log("The area of the rectangle is:", area);

To execute this script, run:
node rectangleArea.js

This script calculates the area of a rectangle with a length of 5 units and a width of 3 units, then prints the result.

Drill #3: Functions and Scoping

(Note scoping also connects to the TDZ which we will cover in a Future Lesson)
Create a file named sumFunction.js and add the following JavaScript code:
function calculateSum(a, b) {
return a + b;
}

// Example of function scoping
let number1 = 8;
let number2 = 12;
const sum = calculateSum(number1, number2);

console.log("The sum of", number1, "and", number2, "is:", sum);

To run this program, use:
node sumFunction.js

This program defines a function calculateSum that takes two numbers and returns their sum. It demonstrates function scoping by accessing variables number1 and number2 defined outside but used inside the function when it is called.
Each of these scripts provides a clear example of the fundamental concepts and practices in JavaScript within a Node.js environment, suitable for initial learning and experimentation.

Drill #4: Objects and Arrays
Create an object representing a book with properties like title, author, and year. Display each property.
error

For Drill #4, Let's create a more complex Node.js script that involves managing a bookstore.

This script will demonstrate modelling books as objects, adding them to an array, and then performing operations like displaying and organizing these books.

Step-by-Step Guide to Creating a Bookstore Management Program

1. Create a File
Create a new file named bookstore.js.
2. Write the JavaScript Code
Below is the code you can write in bookstore.js to manage a simple bookstore:

// Define a class to represent a Book
class Book {
constructor(title, author, year) {
this.title = title;
this.author = author;
this.year = year;
}

// Method to display book details
displayInfo() {
console.log(`Title: ${this.title}, Author: ${this.author}, Year: ${this.year}`);
}
}

// Create an array to store the book objects
let bookstore = [];

// Function to add books to the bookstore
function addBook(book) {
bookstore.push(book);
}

// Function to display all books in the bookstore
function displayBooks() {
bookstore.forEach(book => book.displayInfo());
}

// Create book objects
const book1 = new Book("To Kill a Mockingbird", "Harper Lee", 1960);
const book2 = new Book("1984", "George Orwell", 1949);
const book3 = new Book("The Great Gatsby", "F. Scott Fitzgerald", 1925);

// Add books to the bookstore
addBook(book1);
addBook(book2);
addBook(book3);

addBook(book1);
addBook(book2);
addBook(book3);

// Display all books
console.log("Displaying all books in the bookstore:");
displayBooks();

3. Run the Program
To run this script, navigate to the directory containing your bookstore.js file and execute:
node bookstore.js

Explanation of the Code
Book Class: A simple class Book is defined with properties for the title, author, and publication year, along with a method to display the book's details.
Bookstore Array: An array bookstore is used to store multiple Book objects.
addBook Function: This function takes a Book object as an argument and adds it to the bookstore array.
displayBooks Function: This function iterates over the bookstore array and calls the displayInfo method on each Book object to print its details.
This script showcases how to work with objects and arrays in JavaScript, providing a foundational understanding of managing collections of items, which is common in many real-world applications. The principles demonstrated here are highly applicable across various types of software development tasks involving data management.

Drill #5: Modules
Create a module in calculator.js that exports functions for addition, subtraction, multiplication, and division. Import and use it in index.js.
ok

For Drill #5, we'll set up a simple module system using Node.js. This involves creating two files: calculator.js for the module which contains the arithmetic functions, and index.js for the main script that imports and uses these functions.

Step 1: Create the Module File (calculator.js)

Create a file named calculator.js and add the following JavaScript code:
// Define functions for basic arithmetic operations

function add(x, y) {
return x + y;
}

function subtract(x, y) {
return x - y;
}

function multiply(x, y) {
return x * y;
}

function divide(x, y) {
if (y === 0) {
console.log("Error: Division by zero is not allowed.");
return undefined;
}
return x / y;
}

// Export the functions so they can be used in other files
module.exports = {
add,
subtract,
multiply,
divide
};

Step 2: Create the Main Script File (index.js)

Create another file named index.js in the same directory as calculator.js. Add the following code to import and use the calculator module:

// Import the calculator module
const calculator = require('./calculator');

// Examples of using the imported functions
const sum = calculator.add(5, 3);
const difference = calculator.subtract(10, 4);
const product = calculator.multiply(7, 6);
const quotient = calculator.divide(20, 5);

// Display the results
console.log(`Sum: ${sum}`);
console.log(`Difference: ${difference}`);
console.log(`Product: ${product}`);
console.log(`Quotient: ${quotient}`);

Step 3: Running the Program

To run the program, navigate to the directory containing your files and execute index.js using Node.js:

node index.js

Explanation of the Code

Module Creation (calculator.js): This file defines four functions—add, subtract, multiply, and divide. These functions are then exported using module.exports, making them available to be imported into other JavaScript files.
Module Importing and Use (index.js): This file imports the calculator module using require('./calculator'). It then uses the functions from the calculator module to perform arithmetic operations and prints the results.
This setup exemplifies how modularization in Node.js can help organize and reuse code effectively, allowing you to maintain separate functionalities in different files and import them as needed. This is fundamental for building scalable and maintainable software systems.

Drill #6: Template Literals
Use template literals to create a complex string that includes variables and expressions.
megaphone

For Drill #6, we'll explore using JavaScript ES6 template literals to create complex strings. Template literals are enclosed by backticks (`) and allow embedded expressions, which are expressions included within ${}.

Step-by-Step Guide: Using Template Literals in JavaScript

1. Create a File
Create a file named templateLiterals.js.
2. Write the JavaScript Code
Add the following JavaScript code to templateLiterals.js:
javascript
Copy code
// Define some variables to use within template literals
const user = {
name: "James T. Kirk",
role: "Captain",
ship: "USS Enterprise"
};
const missionCount = 112;

// Create a complex string using template literals
const introduction = `Hello, my name is ${user.name}, and I am the ${user.role} of the ${user.ship}.
I have commanded over ${missionCount} missions across various galaxies.
Today's date is ${new Date().toLocaleDateString()}.`;

// Use template literals to perform calculations directly within the string
const operationalYears = 5;
const report = `As of ${new Date().getFullYear()}, the ${user.ship} has been operational for ${operationalYears} years.
In this time, we've completed ${Math.floor(missionCount / operationalYears)} missions per year on average.`;

// Display the results
console.log(introduction);
console.log(report);

3. Run the Program
To run this script, navigate to the directory containing templateLiterals.js and execute:
bash
Copy code
node templateLiterals.js

Explanation of the Code
Template Literals: The script defines a user object and uses its properties within a template literal to create a detailed introduction. It also demonstrates how to embed JavaScript expressions directly within the template literals, like calculations and method calls (e.g., new Date().toLocaleDateString() and Math.floor()).
Dynamic Content: Template literals support dynamic expressions, which are evaluated at runtime. This allows the inclusion of current dates, calculated values, and other dynamic content directly in strings without concatenation.
Multiline Strings: The example also illustrates how template literals naturally support multiline strings, making them ideal for creating complex, formatted text.
This functionality showcases the power of template literals for creating readable, maintainable code when dealing with complex strings in JavaScript applications, enhancing both functionality and readability.

Drill #7: Spread Operator
Use the spread operator to combine arrays and objects in creative ways.
megaphone

For Drill #7, we'll create an illustrative example using the JavaScript spread operator, specifically for a flower shop scenario. The spread operator (...) is a useful feature in JavaScript that allows elements of an array or properties of an object to be expanded into another array or object. This can simplify combining data, cloning objects, and working with arrays in various operations.

Step-by-Step Guide: Using the Spread Operator in a Flower Shop Context

1. Create a File
Create a file named flowerShop.js.
2. Write the JavaScript Code
Add the following JavaScript code to flowerShop.js to demonstrate the use of the spread operator in managing flower inventories and creating bouquets:
javascript
Copy code
// Initial inventory of flowers in the shop
const roses = ['red rose', 'white rose', 'pink rose'];
const tulips = ['yellow tulip', 'purple tulip', 'orange tulip'];

// Using the spread operator to combine arrays of flowers
const mixedFlowers = [...roses, ...tulips];
console.log('Mixed Flowers Inventory:', mixedFlowers);

// Creating a custom bouquet using selected flowers
const customBouquet = ['blue orchid', ...roses.slice(0, 2), tulips[1]];
console.log('Custom Bouquet:', customBouquet);

// Updating inventory with new shipments
const newFlowers = ['sunflower', 'daisy'];
const updatedInventory = [...mixedFlowers, ...newFlowers];
console.log('Updated Flower Inventory:', updatedInventory);

// Using spread operator to clone and update an object representing a special offer
const specialOffer = { name: 'Spring Bouquet', price: 15 };
const newSpecialOffer = { ...specialOffer, price: 12 }; // Discounted price
console.log('New Special Offer:', newSpecialOffer);

3. Run the Program
To run this script, navigate to the directory containing flowerShop.js and execute:
bash
Copy code
node flowerShop.js

Explanation of the Code
Combining Arrays: The script starts by combining two arrays of different types of roses and tulips into a single mixedFlowers array. This demonstrates how the spread operator can be used to merge lists seamlessly.
Creating Custom Collections: A custom bouquet is created by selectively spreading elements from the roses and tulips arrays. This flexibility allows for tailored compositions, which are common in flower shop offerings.
Updating Inventories: When new shipments arrive, the existing inventory is easily updated by spreading the old and new flower arrays into an updated inventory list.
Cloning and Modifying Objects: The spread operator is also used to clone the specialOffer object and modify its properties in the process, illustrating how you can use it to manage state changes in business scenarios without mutating the original data.
This example provides a practical demonstration of how the spread operator can simplify handling collections of items and objects in JavaScript, particularly useful in dynamic business environments like a flower shop where inventories and offers frequently change.

Drill #8: Asynchronous JavaScript (Callbacks and Promises)
Demonstrate asynchronous JavaScript by fetching data from a public API using Node.js http module.
Drill #9: ES6 Classes
Define a class Person with properties like name and age, and a method to display information about the person.
Drill #10: Introduction to TypeScript
Setup TypeScript in the project: npm install typescript --save-dev and create a tsconfig.json.
Rewrite the Person class using TypeScript, defining types for properties and method arguments.

Closing Session

Q&A: Address any queries from the day’s session.
Assignment: As homework, enhance the TypeScript class by adding additional methods and properties.
Resources: Provide links to further reading materials and official documentation.
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.