Table of contents
- Introduction🚀
- Node.js
- Backend Responsibility
- Node.js Functionality
- Node.js Usage
- Package Manager
- Package manager responsibilities
- NPM (Node Package Manager)
- Package.json: the module manifest
- Package.json File
- Local Install
- Global Install
- Dependencies
- Node.js Modules
- Native Node Module
- Importing Node.js modules
- Export functions & Properties
- Accessing Exported properties
- Purpose of import() & require
- Difference Between require() & import()
- Packages & Specifications
- Initialize a Node.js Project
- Install NPM Package
- Create a simple web server: HTTP
- Asynchronous I/O
- Callback Functions
- Sending an HTTP Request
- HTTP request options & callback
- HTTP response options & callback
- Handling response events
- Handling error events
- Propagating Errors
- Callback with Error Handling
- Passing an error Object
- One Callback at each level
- Promises
- JSON
- Extend Node.js with 3rd party packages
Introduction🚀
Node.js
Node.js is an open-source language that runs on Google Chrome’s V8 engine.
V8 is an open-source engine developed by Google for the Google Chrome browser
It is a server-side programming framework that uses JS as its programming lang
import generateName from "Sillyname";
Heavy emphasis on concurrent programming with a lightweight language.
A single-threaded application that handles results when they are complete.
Backend Responsibility
Load | Scalability | Other Backend Responsibilities |
No. of concurrent users | App ability to handle changes in load affecting performance | Security |
No. of concurrent transactions | Essential for client-server application success | Authentication |
Amount of concurrent data transfer between clients & servers | Malware Prevention | |
Performance |
Node.js Functionality
Developers frequently use js to code client-side capabilities. Node.js is a server component in the same language.
It is event-driven & uses asynchronous , non-blocking I/O
Node.js Usage
Developers can now use Node.js in the same components of the architecture where they use Java, Perl, C++, Python & Ruby
It is used in production by companies like user, PayPal, etc.
Package Manager
A set of tools to deal with modules & packages containing dependencies called a package management system, Maintain a database of dependencies & versioning, Ensure software has correct dependencies
Package manager responsibilities
i) Automate:-
Finding
Installing
upgrading
configuring
maintaining
removing
NPM (Node Package Manager)
It’s a place that collects modules that people have built for Node & the GitHub Organization creates it
NPM comes with a pre-bundled Node
For Node.js, it serves as the default package management.
It provides a CLI to publish & download packages
It behaves as an online repository of JS. package
The repository is a database of packages that tracks package versions.
Package.json: the module manifest
A package consists of one or more modules
Every package has a package.json file that describes details about a Node.js module.
Package.json File
File located in a project’s root directory
NPM uses package.json to determine dependencies
contains key-value pairs that identify the project
Must contain
Project name
Project Version
{
"name" : "thisproject",
"version" : "0.0.1",
}
Local Install
NPM Package can be installed locally or globally
use local install for use with packages within your application
run the local install command from the directory you want the package installed in
Use NPM CLI -
npm install <package_name>
This command creates a directory named node_modules with the package & its dependencies in your current working directory
Global Install
Packages can also be installed globally
All applications on the machine will use a globally installed package
use judiciary
NPM CLI for Global -
npm install -g <package_name>
Dependencies
code in the form of a library or a package revised in a program
Libraries & packages contain many dependencies
A library does not depend on code outside of it to function
Node.js Modules
Every JS file is a module in Node.js
multiple modules can be grouped into a package
Native Node Module
It has many modules for specific purposes & there are many methods present in the modules
Related, encapsulated js code
serves a single purpose
can be a single file or a folder containing files
reusable
Importing Node.js modules
Each Node.js module consisting of a single script uses the required function with a relative path to the script file.
Export functions & Properties
Each Node.js module that consists of a single script uses the required function with a relative path to the script file.
To make a function or a value available to node.js applications that import your modules, add a property to exports
Accessing Exported properties
When you import a Node.js module, the required function returns a JS object representing an instance of the module.
To access the properties of the module, retrieve the property from the variable
Purpose of import() & require
when an external application needs to use the code in a module
ECMAScript Modules
Node 12 version as ECMAScript so here we use the keyword import
as require
a keyword is used in previous versions
Type CJS
var generateName = require("Sillyname");
Type ES
import generateName from "Sillyname";
Difference Between require() & import()
require() - common js | import() - ES |
can be called anywhere in the code | can only be called at the beginning of the file |
can be called with conditionals & functions | cannot be called within conditionals or function |
Dynamic | Static |
Binding errors are not identified until runtime | Binding errors identified at compile time |
Synchronous | Asynchronous |
Import a module use - require() | Import a module use - import() |
Export from a module use - module.exports | Export from a module use -export |
Note - To specify a difference main script for your module, specify a relative path to the node.js script from the module directory
Packages & Specifications
Package - a directory with one or more modules
Module Specifications:- conventions & standards used to create packages, common Js, ES
Initialize a Node.js Project
npm init
Give all information for the package.json file
Hit yes to create it
Install NPM Package
npm install <something>
//Here something is the name of the module
Create a simple web server: HTTP
let server = http.createServer(function(request, response)){
let body = "Hello world!";
response.writeHead(200, {
'content-length' : body.length,
'content-Type' : text/plain
});
resonse.end(body)
});
server.listen(8080);
Asynchronous I/O
Network operations run asynchronously, for ex - the response from a web service call might not return immediately
When an application blocks (or waits) for a network operation to complete, that application wastes processing time on the server.
Node.js makes all network operations in a non-blocking manner
Every network operation returns immediately
To handle the result from a network call, you can write a callback function that Node.js calls when the network operation completes
Callback Functions
A function passes as an argument to another function
Used to ensure an action is executed only after callback
Example -
const message = function(){
console.log("This message is shown after 3 seconds");
}
setTimeout(message,3000);
Sending an HTTP Request
let options = {
host : 'w1.weather.gov',
path : '/xml/current_obs/KSFO.xml'
};
http.request(options, function(response){
let buffer = "";
let result = "";
response.on('data',function(chunk)){ // when the Node.js module calls this anonymous func events occur while receiving parts of the http response message
buffer += chunk;
)};
response.on('end', function(){ //In the actual coding , we may need to use https
console.log(buffer);
});
}).end();
HTTP request options & callback
The HTTP request function calls the callback function parameter when it receives part of the HTTP response
The callback function parameter is optional, you can send an HTTP request & disregard the response message (object)
Example -
http.request(options , [callback function])
HTTP response options & callback
when an HTTP request calls the callback function, it passes a response object in the first parameter
Example -
http.request(options, function(response){ … });
Handling response events
http.request(options , function (response){
let buffer = '';
response.on('data', function(chunk)){
buffer += chunk;
});
response.on('end',function(){
console.log(buffer);
});
}).end();
In node.js, the object.on() func defines an event handler that the framework calls when an event occurs
Forex - the response object in the
http.request
callback function emits events when the node.js module receives parts of the HTTP response message from the remote serverThe response object emits a ‘data’ event when the Node.js module receives a part of the HTTP response message, the response object emits an ‘end’ event
Handling error events
- If the request fails, there is an ‘error’ event followed by the ‘end’ event
request.on('error',function(e){
result callback(e.message);
});
request.end();
- With the http.client Response object, you can :
Write data to the HTTP request message body.
Add headers to the HTTP request message body.
Define an event handler for errors that Node.js encounters while sending the request
- call
clientRequest.end()
to complete sending the request, Ex -request.end()
Propagating Errors
Node.js makes extensive use of callback functions to return the result to the calling function
Node.js modules pass an error object as the 1st parameter in a callback functions
[Call function(error)] - Node.js Modules
|
callback
With this convention, the callback function checks if the first parameter holds an error object.
function (error parameter1 , parameter2 ,..){…}
If an error is defined, the callback function handles the error & cleans up any open network or database connections
If error is not defined, then the callback function examines the result from the call
Callback with Error Handling
weather.current(location, function(error , temp_f){
if(error){
console.error(error);
return;
};
console.log(
"The current weather reading is %s degrees";
temp_f
);
});
response.end("..${temp_f}..")
// If the error parameter is defined , print the error
// Otherwise, the weather.current function call completed successfully
// Print the result from the function call
Passing an error Object
exports.current = function(location, result(callback){
http.request(options , function(response){
let buffer = '';
let result = '';
response.on('data', function(chunck){
buffer += chunk;
});
response.on('end', function(){
parseString(buffer, function(error, result){
if (error){
result callback(erorr);
return;
}
result callback(null , result.current_observation.temp_f[0]);
});
});
});
// If the parseString passes an error object, pass the error back to the result callback function of the origional caller (main application)
//set the first parameter as null if there is no erorr
One Callback at each level
when one Node.js application calls a module in a non-blocking manner, the application must provide a callback function to process the result
If the main application calls a function that calls http.request(), two callback functions are involved:-
The custom module has a callback function to handle the HTTP response message from
http.request()
The main application has a callback function that processes the result captured in the 1st callback function
Promises
An object returned by an asynchronous method
States: pending, resolved, rejected
Uses: API requests, I/O Operations
JSON
JSON is mostly used for API data exchange because it is the standard representation of JS Objects, Node.js handles JSON easily
We have a method in javascript known as
JSON.parse()
, this method used to parse a JSON string to a JS objectWe have another method known as
JSON.stringify()
, this method used to convert a JS object to a JSON string
Extend Node.js with 3rd party packages
The Node.js provides a small amount of features for building apps.
For Example, Node.js does not provide a parsing function for extensible markup language(XML) messages.
Developers rely on 3rd party packages to extend Node.js features
Conclusion
Follow Me On Socials :
Like👍| Share📲| Comment💭