Tuesday, June 16, 2020

NodeJs basic concepts

It is a server side runtime environment for java script running on google chrome v8 machine that allows java script to run on server side stand alone machine as a applications. Hence Nodejs is not a language. It has following benefits
1- It is Event driven. Means as in this we have event that is fired and depending on the type of event listener catch it and perform operations.
2- It is non blocking i.e. if we get three hit or nodejs request all are executed at the same time and one which complete the processing will be given the result first. It is not like old fashion where all ther request are queued and depending on FIFO algo they are taken for request processing on availability of server.
3- It is lightweight, fast and highly recommended for real time applications.
you can download the latest stable version of nodejs from https://nodejs.org/en/download/
Make sure to install both node and npm and check the version of Node and Npm using command
node -v
npm-v
to check if the nodejs is working fine on your machine just print node and perform this simple example
PS C:\Visual_Source_Code_WorkSpace_NodeJS\nodejsexample> node
Welcome to Node.js v14.2.0.
Type ".help" for more information.
> console.log ("hello world")
hello world
undefined
Now lets start to set up the working folder for the nodejs that we are going to us for our demo small projects.
I am using Microsoft Visual Source Code as an IDE which comes with inbuild many nodejs plugin for ease of development.
First we will set the working folder and then we will run the command as
npm init
This will create a package.json file that will contains all the base module that we are going to use in our application. In real world scenario we give our code with package.json file. At run time the developer/tester or Production/SAT environemnt can create the whole project just by running
npm install
The above command will by default look into package.json and install all the module register into that are mandate to running our application.
Whern we run npm init it will ask for some default informaion fill it and it wil create package.json files.
PS C:\Visual_Source_Code_WorkSpace_NodeJS\nodejsexample> npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.
See `npm help json` for definitive documentation on these fields
and exactly what they do.
Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.
Press ^C at any time to quit.
package name: (nodejsexample) nodejsexample
version: (1.0.0)
description: This package containes nodejs exmaple
entry point: (index.js)
test command:
git repository: (https://github.com/shdhumale/nodejsexample.git)
keywords:
author: Siddaratha dhumale
license: (ISC)
About to write to C:\Visual_Source_Code_WorkSpace_NodeJS\nodejsexample\package.json:
{
"name": "nodejsexample",
"version": "1.0.0",
"description": "This package containes nodejs exmaple",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git+https://github.com/shdhumale/nodejsexample.git"
},
"author": "Siddaratha dhumale",
"license": "ISC",
"bugs": {
"url": "https://github.com/shdhumale/nodejsexample/issues"
},
"homepage": "https://github.com/shdhumale/nodejsexample#readme"
}

Is this OK? (yes) y
1- Package.json
{
"name": "nodejsexample",
"version": "1.0.0",
"description": "This package containes nodejs exmaple",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git+https://github.com/shdhumale/nodejsexample.git"
},
"author": "Siddaratha dhumale",
"license": "ISC",
"bugs": {
"url": "https://github.com/shdhumale/nodejsexample/issues"
},
"homepage": "https://github.com/shdhumale/nodejsexample#readme"
}
now let create a new nodejs file and name it as siddhu.js

console.log("Hello world")
var a = 10
var b = 20
console.log(a + b)

and execute it using command as
PS C:\Visual_Source_Code_WorkSpace_NodeJS\nodejsexample> node .\siddhu.js
Hello world
30
3- Object, Anonymous and Arrow Function:-
In node js we can create an object as shown below
var user = { name: 'siddhu', surname: 'dhumale' }
console.log(JSON.stringify(user))
PS C:\Visual_Source_Code_WorkSpace_NodeJS\nodejsexample> node .\siddhuobject.js
{"name":"siddhu","surname":"dhumale"}

'- Anonymous funtoin :- This are the funtion which has no name we can define it as
var user = function (a) {
console.log("values are" + a)
}
user(10)
PS C:\Visual_Source_Code_WorkSpace_NodeJS\nodejsexample> node .\annonymus.js
values are10
'- Arrow funtion
const user = () => {
console.log("hello Arrow function")
}
user();
PS C:\Visual_Source_Code_WorkSpace_NodeJS\nodejsexample> node .\annonymus.js
hello Arrow function
4- Global Objects in node js:-
These are the few of the global object that are predefined object and user can use it as it is defualt available to the user while development
1- Dirname - give the directory names.
2- filename - give the file name full file name with paths.
3- exports - use to export the module/class/components so that it can be used by other component in the application.
4- console - use to print the value on prompt
5- module - this is used to export the module class/components etc
6- buffer
7- requires : to import the package that we are going to use in our applications.

'- anonymus.js
var user = function (a) {
console.log("values are" + a)
}
function testExport(a, b) {
var c = a + b
console.log("ans" + c)
}
user(10)
module.exports.user = user
module.exports.testExport = testExport
'- importtest.js
var user = require('./annonymus')
console.log('---------user---------------' + JSON.stringify(user))
console.log('-----------testExport-------------' + JSON.stringify(user.testExport(2, 3)))
output:-
PS C:\Visual_Source_Code_WorkSpace_NodeJS\nodejsexample> node .\importtest.js
values are10
---------user---------------{}
ans5
-----------testExport-------------undefined

5- Some basic concept of What is ECMAScript
var, const and let
a) const :-
means it is consant and canno be changed but once you define it as an object it will allow you to change
const a =10
const a =20
//this will give error
const a = {
name:"siddharatha",
surname:"dhumale"
}
console.log(a.name)
output :- siddharatha
we can also modify it
const a = {
name:"siddharatha"
surname:"dhumale"
}
a.address="india"
//or a.name="siddhu"
console.log(a.address)
output :- india

b) let
can be used in templage literal
This means we cannot define same varibale again like const
let a =10
let a =20
//this will give error
but we can do the same in functions
let a = 10
function test()
{
let a= 20
console.log(a)
}
console.log(a)
test()
output:-
10
20
c) var
This will give the latest valye of the variable with out any error. it will allow duplicates.
var a=10
var a= 20
console.log(a)
Output :- 20
d) String literal
/* const a = {
name: "siddharatha",
surname: "dhumale"
}
a.name = "siddhu"
console.log(a.name) */
var a = "siddhu"
var b = "dhumale"
console.log("First name " + a + " surname " + b)
console.log(`string literal First name ${a} surname ${b}`)
output :-
PS C:\Visual_Source_Code_WorkSpace_NodeJS\nodejsexample> node .\ecmsscript.js
First name siddhu surname dhumale
string literal First name siddhu surname dhumale
6- Prototype
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}
Person.prototype.nationality = "English";
var myFather = new Person("John", "Doe", 50, "blue");
console.log(myFather.nationality)
PS C:\Visual_Source_Code_WorkSpace_NodeJS\nodejsexample> node .\prototype.js
English

7- Module in node.js
Module is similar to package in java. It has collection of component that has unique functionality to be addressed.
Consider modules to be the same as JavaScript libraries.A set of functions you want to include in your application.
Let take example we are creating four component or module add,sub,div and mul for math operation
a) add.js
function add(a, b) {
return a + b
}
module.exports.add = add
b) sub.js
function sub(a, b) {
return a - b
}
module.exports.sub = sub
c) mul.js
function mul(a, b) {
return a * b
}
module.exports.mul = mul
d) divide.js
function divide(a, b) {
return a / b
}
module.exports.divide = divide
e) calculator.js
var add = require('./add')
var sub = require('./sub')
var divide = require('./divide')
var mul = require('./mul')
console.log(add.add(1, 2))
console.log(sub.sub(5, 2))
console.log(divide.divide(8, 2))
console.log(mul.mul(1, 2))
output:-
PS C:\Visual_Source_Code_WorkSpace_NodeJS\nodejsexample\calculator> node .\calculator.js
3
3
4
2

8- Http Module
This is the module used for making http request to fetch the data from the external webservice.
Lets first use for creating simple node http server
a) httpserver.js

first we have to require handle for http module using
var http = require('http');
after that we have to create a server using createServer function from http module
http.createServer()
Now also give listening port to http
http.createServer().listen(4000)
Now lets run this file and see the browser hitting url
http://localhost:4000
you will see you did not get any output on the screen and that is because we did not send any response back to broser. Now lets do that

var http = require('http');
http.createServer(
function (req, res) {
//below res inform what to do with the response.
res.write("hello world")
//below command indicate res is end and ready render the screen on the browser
res.end()
}
).listen(4000)
Now lets run this file and see the browser hitting url
http://localhost:4000
you will see hello world on the screen
Image11
9- Nodemon Installation
https://www.npmjs.com/package/nodemon
Additional when we start the server we did not get anything on the console that indicate that server is started for that we can add console.log as shown below
var http = require('http');
http.createServer(
function (req, res) {
res.setHeader("Content-Type", "html");
//res.setHeader("Content-Type", "text/plain");
res.write("<h1>hello world</h1>")
res.end()
}
).listen(4000, console.log("Server started"))

Now as you can see everytime we changes the node files we always need to restart the server once again to get ride of this we need to install nodemon.
we can install nodemon using below command. Generally it is prefered to install nodemon on global level.
npm install -g nodemon
or for dev mode
npm install --save-dev nodemon

to run the application make changes in package.json like this
"main": "./HttpModule/httpmodule.js",
"scripts": {
"start": "nodemon",
"test": "echo \"Error: no test specified\" && exit 1"
},

and use this command
npm start .\httpmodule.js
Note: If you get below error then follow the solution given below.
PS C:\Visual_Source_Code_WorkSpace_NodeJS\nodejsexample\HttpModule> nodemon
nodemon : File C:\Users\Siddhartha\AppData\Roaming\npm\nodemon.ps1 cannot be loaded. The file C:\Users\Siddhartha\AppData\Roaming\npm\nodemon.ps1 is not digitally
signed. You cannot run this script on the current system. For more information about running scripts and setting execution policy, see about_Execution_Policies at
http://go.microsoft.com/fwlink/?LinkID=135170.
At line:1 char:1
+ nodemon
+ ~~~~~~~
+ CategoryInfo : SecurityError: (:) [], PSSecurityException
+ FullyQualifiedErrorId : UnauthorizedAccess

Solutions:-
1- PS C:\Visual_Source_Code_WorkSpace_NodeJS\nodejsexample\HttpModule> Get-ExecutionPolicy
Unrestricted
2- PS C:\Visual_Source_Code_WorkSpace_NodeJS\nodejsexample\HttpModule> Get-ExecutionPolicy -list
Scope ExecutionPolicy
----- ---------------
MachinePolicy Undefined
UserPolicy Undefined
Process Undefined
CurrentUser Undefined
LocalMachine Unrestricted
3- PS C:\Visual_Source_Code_WorkSpace_NodeJS\nodejsexample\HttpModule> Set-ExecutionPolicy unrestricted
For more information refer to the site
https://www.opentechguides.com/how-to/article/powershell/105/powershel-security-error.html
http://mvsourcecode.com/powershell-ps1-is-not-digitally-signed-you-cannot-run-this-script/
Now start the applicatoin using
PS C:\Visual_Source_Code_WorkSpace_NodeJS\nodejsexample\HttpModule> nodemon .\httpmodule.js
[nodemon] 2.0.4
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node .\httpmodule.js`
Server started
[nodemon] restarting due to changes...
[nodemon] restarting due to changes...
[nodemon] starting `node .\httpmodule.js`
Server started
10 - File System Module in node.js
Now lets understand the File operation using file module of Nodejs. As we know Nodejs is server side language it has capability to create/delete/update the file present on the server using this modules.
to use this module we need to use package called "fs"
var fs = require('fs');
fs.readFile(__dirname + "/siddhu.txt", "utf-8", (err, data) => {
if (err) {
console.log(err);
}
else {
console.log(data);
}
}
)
PS C:\Visual_Source_Code_WorkSpace_NodeJS\nodejsexample\Files> node .\fileoperation.js
This is siddhu text files used

You can also delete the file using below unlink
fs.unlink(__dirname + "/siddhu.txt", (err, data) => {
if (err) {
console.log(err);
}
else {
console.log("Files deleted:");
}
})
Now lets read the files from the text files and divert it to browser

var http = require('http');
var fs = require('fs');
http.createServer(
function (req, res) {
fs.readFile(__dirname + "/siddhu.txt", "utf-8", (err, data) => {
if (err) {
console.log(err);
}
else {
console.log("Read data:" + data);
res.setHeader("Content-Type", "text/plain");
//res.setHeader("Content-Type", "text/plain");
res.write(data)
res.end()
}
}
)
}
).listen(4000, console.log("Server started"))
Image2
11- Sync and Async function in file system
Difference between Sync and Async is that for Async the programe did not waite for data to come but it execute the next line in the programe.
Let me show you with this exmaple. By defualt all the function in Nodejs FS module is Asyn in nature

a) var fs = require('fs');
fs.readFile(__dirname + "/siddhu.txt", "utf-8", (err, data) => {
if (err) {
console.log(err);
}
else {
console.log(data);
}
}
)
console.log("ASync programing")
If we execute above programe we will get
Output:-
ASync Program
Read data:This is siddhu text files used
As you see above "ASync Program" is printed first before real output of the file that is our programe did not waite for the output to come but directly execute the next line the programe and after that when it get the response from the files it show the files data.
b)
try {
var syncdata = fs.readFileSync(__dirname + "/siddhu.txt")
console.log("Read data:" + syncdata);
console.log("Sync Program")
}
catch (exception) {
console.log(exception)
}
Output:-
Read data:This is siddhu text files used
Sync Program

12- Events, Custom Events and Trigger Custom Event in Node.js
NodeJs is event driven languages. Means we fire the action or event and depending on the type of event of action we perform operations. For that we use event module
var event = require("event")
Let take one example

var events = require('events')
var eventEmitter = new events.EventEmitter()
//Assign the event handler to an event:
eventEmitter.on('scream', () => { console.log("this function is fired using eventemitter") });
//Fire the 'scream' event:
eventEmitter.emit('scream');
OutPut:-
PS C:\Visual_Source_Code_WorkSpace_NodeJS\nodejsexample\events> node .\eventscript.js
this function is fired using eventemitter
We can also write the above code as
var events = require('events')
var eventEmitter = new events.EventEmitter()
/* function printLog() {
console.log("this function is fired using eventemitter")
}
*/
/* var printLog = function () {
console.log("this function is fired using eventemitter")
}
*/
var printLog = () => {
console.log("this function is fired using eventemitter")
}
//Assign the event handler to an event:
eventEmitter.on('scream', printLog)
//Fire the 'scream' event:
eventEmitter.emit('scream');

Now lets to execute the programe that will fire the event and then read the data from the files.

var events = require('events')
var eventEmitter = new events.EventEmitter()
var fs = require('fs');
/* function printLog() {
console.log("this function is fired using eventemitter")
}
*/
/* var printLog = function () {
console.log("this function is fired using eventemitter")
}
*/
var printLog = () => {
console.log("this function is fired using eventemitter")
fs.readFile(__dirname + "/../Files/" + "/siddhu.txt", "utf-8", (err, data) => {
if (err) {
console.log(err);
}
else {
console.log("Read data:" + data);
}
}
)
}
//Assign the event handler to an event:
eventEmitter.on('scream', printLog)
//Fire the 'scream' event:
eventEmitter.emit('scream');

Output:-
PS C:\Visual_Source_Code_WorkSpace_NodeJS\nodejsexample\events> node .\eventscript.js
this function is fired using eventemitter
Read data:This is siddhu text files used
We can also have nested event call i.e event calling the other event call.
var events = require('events')
var eventemitter = new events.EventEmitter()
var firstevent = (a, b) => {
console.log("first event trigger " + a * b)
eventemitter.emit("second_event")
}

var secondevent = () => {
console.log("second event trigger")
eventemitter.emit("third_event")
}
var thirdevent = () => {
console.log("third event trigger")
}
//on is used to listen the event
eventemitter.on("first_event", firstevent)
eventemitter.on("second_event", secondevent)
eventemitter.on("third_event", thirdevent)
//emit is used to fire the event
eventemitter.emit("first_event", 10, 20)

Output:-
PS C:\Visual_Source_Code_WorkSpace_NodeJS\nodejsexample\events> node .\nestedevent.js
first event trigger 200
second event trigger
third event trigger

No comments: