Unit 3
Unit 3
js
• Node.js is a server-side platform built on Google Chrome's JavaScript Engine (V8 Engine).
• Node.js was developed by Ryan Dahl in 2009.
• It is for easily building fast and scalable network applications.
• Node.js uses an event-driven, non-blocking I/O model.
• that makes it lightweight and efficient, perfect for data-intensive applications that run across
distributed devices.
• Node.js is an open source, cross-platform runtime environment for developing server-side and networking
applications.
• Node.js retrieves the incoming requests and adds those requests to the Event Queue
• The requests are then passed one-by-one through the Event Loop. It checks if the
requests are simple enough to not require any external resources
• Event Loop processes simple requests (non-blocking operations), such as I/O Polling,
and returns the responses to the corresponding clients
A single thread from the Thread Pool is assigned to a single complex request. This thread is
responsible for completing a particular blocking request by accessing the external resources,
such as compute, database, file system, etc.
Once, the task is carried out completely, the response is sent to the Event Loop that in turn
sends that response back to the Client
A Node.js application consists of the following three important
components −
Go to the command line interface, write node myfirst.js and hit enter:
Node Module System
•The Node.js module system is a key feature that enables developers to organize,
encapsulate, and manage their code in a modular and efficient manner.
•It allows developers to break down their code base into smaller, reusable components
called modules, which can be shared and imported as needed.
•This system plays a crucial role in promoting code maintainability, reusability, and
collaboration in Node.js applications.
All of these arguments get their values when Node executes the wrapper function. exports is defined as a
reference to module.exports prior to that. require and module are both specific to the function to be executed,
and __filename/__dirname variables will contain the wrapped module’s absolute filename and directory path.
fs (File System): This module provides methods for working with the file system,
allowing you to read, write, and manipulate files and directories.
//ex1:
const fs = require("fs");
let text = fs.readFileSync("dele.txt", "utf-8");
text = text.replace("browser", "Rohan");
//ex2
const fs = require("fs");
fs.readFile("dele.txt", "utf-8", (err, data) => {
console.log(err, data);
});
console.log("This is a message");
http: The http module is used for creating HTTP servers and making HTTP requests. It's the
foundation of building web applications and APIs.
Path.join takes an array of path segments and joins them together using the platform-
specific separator.This method is more reliable when compared to string concatenation
because of extra caution to be taken for supporting multiple platforms.
//join
console.log(path.join("folder1", "folder2", "index.html"));
console.log(path.join("/folder1", "folder2", "index.html"));
console.log(path.join("/folder1", "//folder2", "index.html"));
console.log(path.join("/folder1", "//folder2", "../index.html"));
console.log(path.join(__dirname, "data.json"));
//Path.dirname is a helper method to get the parent directory for the given path
var path = require("path");
// //Return the directries:
var directories = path.dirname("/Users/Refsnes/fg.js");
console.log(directories);
//Path module has a basename method to get the file name part
const path = require("path");
console.log(__filename);
console.log(__dirname);
//basename
console.log(path.basename(__filename));
console.log(path.dirname(__dirname));
//extname
console.log(path.extname(__filename));
console.log(path.extname(__dirname));
//parse
console.log(path.parse(__filename));
console.log(path.parse(__dirname));
//isabsolute
console.log(path.isAbsolute(__filename));
console.log(path.isAbsolute("./data.json"));
os (Operating System): This module provides information about the operating system's CPU, memory, network
interfaces, and other related details.
const os = require("os");
console.log(os);
console.log(os.freemem());
console.log(os.freemem() / (1024 * 1024 *
1024));
console.log(os.totalmem() / (1024 * 1024 *
1024));
console.log(os.hostname());
console.log(os.platform());
console.log(os.userInfo());
url: The url module offers utilities for parsing and formatting URLs.
//Parse a query string into an object, and extract the year property:
const querystring = require("querystring");
//const queryString = "param1=value1¶m2=value2";
const queryString = "ocid=msedgntp&cvid=6010b9ead85c42139a8749d3fc185e16&ei=9";
const parsedQuery = querystring.parse(queryString);
console.log(parsedQuery); // Output: { param1: 'value1', param2: 'value2' }
console.log(parsedQuery.cvid);
module.exports = {
add,
subtract,
};
Loading and Using the Module:
Require the Module: In another JavaScript file (let's call it main.js), you can use the require function to load the
math.js module:
// main.js
const mathModule = require("./mathx");
console.log(mathModule.add(5, 3));
console.log(mathModule.subtract(10, 4));
Run the Main File: Run the main.js file using Node.js:
node main.js
This will output the results of the addition and subtraction operations defined in the math.js module.
Remember that the require function takes the path to the module file as an argument. You can use either a relative path
(starting with ./) or an absolute path.
Exporting Different Types:
You can export various types of values from a module, including variables, functions, classes, or even an entire object. The
module.exports object allows you to define what parts of the module are accessible when the module is imported using require.
This is the basic process of creating and loading a module in Node.js. By organizing your code into modules, you can maintain a
clean and modular codebase, reuse code efficiently, and improve collaboration among team members.
Global Object:
The global object provides access to various global properties and functions that are available throughout your application
without the need to import them explicitly. While this might sound similar to the global scope in a browser's JavaScript
environment, it's important to note that the Node.js global object is not as extensive as the browser's global scope.
Some commonly used properties and functions available on the Node.js global object:
1. Global Variables:
global: This property refers to the global object itself. It's equivalent to this in the global scope.
2. Console:
console: Provides methods for logging and interacting with the console.
console.log(), console.error(), console.warn(), etc.
3. Timers:
setTimeout(), setInterval(), setImmediate(): Functions to schedule asynchronous operations.
4.Buffers:
Buffer: The Buffer class for working with binary data.
5.Paths and Directories:
__dirname: The directory name of the current module.
__filename: The full path to the current module file.
require(): A function to import modules.
6.Process:
process: Provides information and control over the current Node.js process.
process.argv: An array containing command-line arguments.
process.env: An object containing environment variables.
process.cwd(): Returns the current working directory.
process.exit(): Terminates the Node.js process.
7.Modules and Exports:
module: A reference to the current module object.
exports: An object used to define what a module exports.
8.Error Handling:
Error: The constructor function to create error objects.
9.Utilities:
setInterval(), setTimeout(): Functions for scheduling repeated or delayed execution of functions.
It's important to note that while these properties and functions are available globally, it's generally considered better practice
to avoid polluting the global scope and to use module-level scoping instead. This means that you often declare and use
variables, functions, and classes within the scope of a module, making them accessible only where needed. This approach
promotes better code organization, reusability, and maintainability.
For example, instead of using the global setTimeout(), you might use it within a specific modu// app.js
setTimeout(() => {
console.log('Delayed message');
}, 1000);
3Rd party example:-
const capitalize = require('capitalize)
And then you can use it in your code, like this for example:
module.exports is an object in a Node.js file that holds the exported values and
functions from that module.
It is the object reference that gets returned from the require() calls.
It is automatically created by Node.js.
It is just a reference to a plain JavaScript object.
Exports alias
“exports” is just a convenience variable so module authors can write less code
Working with its properties is safe and recommended.
(eg.: exports.add = function…)
Exports is NOT returned by require()
exports.value1 = value1
exports.function1 = function1
const function1 = function() {
const value1 = 50 console.log("I am a function")
exports.value1 = value1 }
module.exports = { function1, ...module.exports }
console.log(module)
// { console.log(module)
// id: ".",
// path: "...", // {
// exports: { value1: 50 }, // id: ".",
// parent: null, // path: "...",
// filename: "...", // exports: { function1: [Function: function1] },
// loaded: false, // parent: null,
// children: [], // filename: "...",
// paths: [ // loaded: false,
// ... // children: [],
// ], // paths: [
// } // ],
// }
Node Package
Manager(NPM)
NPM (Node Package Manager) is the default package manager for Node.js and
is written entirely in Javascript. Developed by Isaac Z. Schlueter, it was initially
released in January 12, 2010. NPM manages all the packages and modules for
Node.js and consists of command line client npm
Node Package Manager (NPM) is a command line tool that installs, updates or
uninstalls Node.js packages in your application.The node community around the
world creates useful modules and publishes them as packages in this repository.
It allows us to use code written by others easily without the need to write them
ourselves during development.
The required packages and modules in Node project are installed using NPM.
A package contains all the files needed for a module and modules are the JavaScript
libraries that can be included in Node project according to the requirement of the project.
a CLI (command-line interface) tool for publishing and downloading packages, and
an online repository that hosts JavaScript packages
Package Manager vs. Package Registry
A package manager is a tool developers use to automatically find, download, install, configure, upgrade, and
uninstall a computer's packages.
NPM (Node Package Manager) and Yarn (Yet Another Resource Negotiator) are two popularly used package
managers.
A package registry is a database (storage) for thousands of packages (libraries, plugins, frameworks, or tools).
In other words, a package registry is the place packages get published to and installed from.
NPM registry and GitHub Packages are two popularly used package registries.
To check the NPM version installed on your system, run:
npm -v
A package is a directory (or project) that has a package.json file used to record information about it.
the --save command above instructs NPM to save package-name in the package.json file as one of the
packages on which the project depends.
The commands above will cause NPM to download three items into your project's root directory: a
node_modules folder, a package.json file, and a package-lock.json file
Global package installation
A globally installed package is a package that you can use anywhere on your system.
You can do both local and global installation of packages you intend to use both on the command line
and in your project. Typical examples of such packages are ExpressJS and CoffeeScript.
Your package manager does not execute an installed package. NPM (and Yarn) only install packages to
the node_modules directory. And if you had specified the --save command, your manager would add
details about the package to the package.json file.
To execute (run) any executable package, you must explicitly do so yourself.
package.json
The package.json file is the heart of any Node project. It records important metadata about a project which is
required before publishing to NPM, and also defines functional attributes of a project that npm uses to install
dependencies, run scripts, and identify the entry point to our package
The package.json file helps us keep track of all the installed packages in a given project. When creating a
new project, it is important to start by creating this file.
npm init
The package.json file contains the metadata information. This metadata information in package.json file can
be categorized into below categories.
Identifying metadata properties: It basically consist of the properties to identify the module/project such as
the name of the project, current version of the module, license, author of the project, description about the
project etc.
Functional metadata properties: As the name suggests, it consists of the functional values/properties of the
project/module such as the entry/starting point of the module, dependencies in project, scripts being used,
repository links of Node project etc.
package-name: As you learned earlier in this tutorial, the name of your package must be unique. Also it
must be lowercase. It may include hyphens.
version: The initial value is 1.0.0. You update the number when you update your package using semantic
versioning.
description: You can provide a description of your package here. Indicate what your package does and how
to use it.
entry point: The entry file for your code. The default value is index.js.
test command: Here, you can add the command you want to run when a user runs npm run test.
git repository: The link to your remote repository on GitHub.
keywords: Add relevant keywords that will help others find your package on the NPM registry.
author: Add your name.
license: You can add a license or use the default license (Internet Systems Consortium (ISC) License
The node_modules directory is the folder where NPM places all the packages it
downloads locally for your project.
The package-lock.json file is a document NPM uses to record the exact version of all the
packages you've installed locally to your project's node_modules directory.
A package-lock.json file makes an app 100% reproducible in the exact way you published it
to the NPM registry.
Dependencie: Packages required by your application in production.
Dependency is an object that contains the library, which your project requires for production environments and
functioning effectively. You require these packages to test and run your project on the localhost.
whenever a user installs your project from the NPM registry, the dependencies property ensures package managers
can automatically find and install the packages listed.
Note that you can add a package to the "dependencies" field through either of the following ways:
Manually add the name and the semantic version of each package your project depends on in production.
These types of dependencies are required during the web application development process but not while testing or
executing it. Whenever you add a library or module that is required only in the development of your project, you can find
it under devDependencies
For adding devDependencies to your project, run the below command:
Manually add the name and the semantic version of each package on which your project depends for its development and
testing purposes.
Run the npm install package-name --save-dev command on your terminal. Or yarn add package-name --dev if Yarn is
your package manager.
"name": "dev_dependencies",
"version": "1.1.0",
"dependencies": {
"my_dep": "^1.1.0",
"another_dep": "~2.1.0"
},
"devDependencies" : {
"my_test_framework": "^3.2.0".
"another_dev_dep": "1.1.0 - 1.3.0"
}
Installing a Node Package
There are two ways to install a package: locally or globally.
Local package installation
A locally installed package is one that you can use only in the project in which you've installed it.
To install a package locally, do the following:
Navigate to the root directory of your project from the command line.
Install your package using the NPM installation command
npm install package-name --save
Note:- that the --save command above instructs NPM to save package-name in the package.json file as one of the packages on
which the project depends.
Initialization:
Middleware Execution:
Routing:
Error Handling:
Response Sent:
app.get('/api/data', (req, res) => {
const data = { key: 'value' };
res.json(data);
});
Installation and the First Program
To install Express JS on your system first you need to install node js then we will write a command to install express in the
terminal.
app.get('/',(req, res)=>{
res.send('Hello World!')
})
app.listen(port,()=>{
console.log(`Example app listening on port ${port}`)
})
Routing refers to determining how an application responds to a client request to a
particular endpoint, which is a URI (or path) and a specific HTTP request method (GET,
POST, and so on).
Each route can have one or more handler functions, which are executed when the route is
matched.
app.METHOD(PATH, HANDLER)
Where:
// respond with "hello world" when a GET request is made to the homepage
app.get('/', (req, res) => {
res.send('hello world')
})
The request (req) and response (res) objects are fundamental components of handling HTTP requests and
generating HTTP responses. They come with various properties and methods that allow you to access and
manipulate different aspects of the HTTP transaction. Below are some of the commonly used properties and
methods of the req and res objects:
3. req.body:Contains the parsed request body for POST and PUT requests.
app.post('/users', (req, res) => {
const userData = req.body;
});
4.req.headers:Contains the headers sent with the request.
const contentType = req.headers['content-type’];
6.req.method:Contains the HTTP method of the request (GET, POST, PUT, DELETE, etc.).
const httpMethod = req.method;
Config.js
module.exports = {
port: process.env.PORT || 3000
};
Index.js
const express = require('express');
const config = require('./config');
const app = express();
app.listen(config.port, () => {
console.log(`Server is running on port ${config.port}`);
});
A config file can also export separate variables that hold the values or a simple object with custom depth level
so we can also give scope to the config elements.This is far from perfect as every time we want to change a
config value, we have to touch the code. We can overcome this with the help of environment variables
In Node.js and Express.js, you can read configuration parameters from various sources, such as environment
variables, configuration files, command line arguments, or a combination of these. Here's a basic guide on how
you can achieve this:
app.listen(port, () => {
console.log("server has started...");
});