Download as pdf or txt
Download as pdf or txt
You are on page 1of 54

26/10/2023

JS - ES5

ES6 - es2015 - modern js

ES2023 - current version of js

class
arrow function
let const

task:
=====
class
filter()
map()
foreach()
arrow function
this keyword

node download
==============
https://nodejs.org/en/download

verify:
============

C:\Users\kathiresann>node -v
v16.13.0

C:\Users\kathiresann>npm -v
8.1.0

browser - js engine

chrome - V8
safari - nitro, javascriptCore
firefox - spider monkey
edge - chakra
Node js - uses V8 engine - modified -> node engine
created by Ryan dahl - 2009

asynchronous event-driven JavaScript runtime

Javascript:
============
datatype -
loosely typed
var -

10
hi hello
4.5
true
A

var a=90;
a='hi'
a=true

variable datatype is based on rgt hand side value

Number, boolean, symbol, string,


object,array

27/10/2023

Javascript:
=============

let var const:

loosely typed - no fixed datatype

datatypes

var a=90; //number


//10 lines
a= "hello"
a? string

scopes :

visibility

function scope
global scope
local scope - ES6

var a=90; //global

function get(){
var b=90; //function scope
console.log(b);
console.log('a value is ',a);
}

function get1(){
var c=90; //function scope
console.log(c);
console.log('a value is ',a);
}

var a - get,get1......

var b - get
var c - get1

local/block scope: use only let,const

similiar to function scope

block - { ... }
block can be a empty {...} or if block or else, elseif or while or do...while or for... etc, nested
function

function get(){
var a=9890;
console.log('before -a val is',a);
// anonymous
{
var a=90;
console.log('a inner val is',a);
}
console.log('after block a val is',a);
}
get()

ans:

before -a val is 9890


a inner val is 90
after block a val is 9890

global scope: visible to all function

var a=3000;

function one(){
console.log('in func 1',a);
}

function two(){
console.log('in func 2',a);
}

one()
two()

problem:
=========
var a=3000; //global scope
function one(){
var a=897;//function scope
console.log('in func 1',a);//897
//solution
console.log('global val of a ',this.a) //window obj
console.log(this)
}

function two(){
console.log('in func 2',a);
}

one()
two()

let vs const-

function check(){
const o=90;
o=8000;
console.log(o)
}

function check(){
let o=90;
o=8000;
console.log(o)
}
===============================

parameter - function definition

eg: funct chk(ab){} --- here ab is a parameter

arguments: when func called


eg: func chk(ab) {}
chk(90)// 90 is arg
var t=90;
chk(t) // t is arg

default parameter:
===================
function say(message) {
console.log(message);
}

//message - parameter
s="hello"
say(s) // s- argument

what if we dont pass value for s?????

say() --- prints undefined -cause below erro


============================================================
IMPORTANT:
============
a=90
90
a.toLocaleString()
'90'
a=undefined
undefined
a.toLocaleString()
VM494:1 Uncaught TypeError: Cannot read properties of undefined (reading 'toLocaleString')
at <anonymous>:1:3
==============================================================
Solution: default paratemer
=========

function say(message='hi') {
console.log(message);
}
say('hello') //hello
say() //hi

function say(message='hi',msg2) {
console.log(message);
}

JavaScript Rest Parameter -it is represented -> ... (triple dot) followed by var_name
==========================
rest parameter is a kind of array

Rest parameter must be last formal parameter --IMP NOTE


function restCheck(a,...rem){

console.log(a)
console.log('remaining values are ',rem)
}

restCheck(9,8,98,76)

function restCheck(a,b,c,...rem){

console.log(a,b,c)
console.log('remaining values are ',rem)
}

restCheck(9,8,98,76,78,56)

=========================================
spread operator: symbol same ...(triple dot) then var_name
================
used for extraction an array or object

var arr=[9,8,98,76,78,56] //keep it as zipping files

function restCheck(a,b,...rem){

console.log(a,b)
console.log('remaining values are ',rem)
}
restCheck(...arr); //spread - unzipping

30/10/2023
template literals: `` + ${}
============================
var res=`his name ${name}, his age is ${age}`
undefined
res
'his name ajay, his age is 23'
var res=`his name ${name}, his age is ${age}. his sal is ${12*3000+900}`
undefined
res
'his name ajay, his age is 23. his sal is 36900'

multiline support:
====================
var res=`hi
Hello`

Arrays and methods:


===================

var arr=[1,2,3,34,4,5]

console.log(arr[0])

functions:
=============

function fn(param){}
function fn(param){
return something;
}
fn() - function call

anonymous function:

let get=function(param){
return something;
}

console.log(get)
console.log(get())
variable hoisting:
==================
po=90; console.log(po); var po; //hoisting
po1=90; console.log(po1); let po1; //let avoids hoisting

function hoisting:
===================

get1(); after 1000th line ---> function get1(){ console.log('hi')}

if used let , function hoisting is avoided

to make a function not to be hoisted we declare function as anonymous


function ie store the function in let or var

get2();

let get2=function()
{
console.log('hi')
}

arrow function:
==================

let get3=()=>console.log('hi')
get3()
let get4=()=>'hi welcome'
get4()

let add=(n1,n2)=> {
var res=n1+n2;
res=res-1
var final=res*2;
return final;
}
add(1,2)

let add=(n1,n2)=> n1+n2; //adds and returns the result automatically


add(1,2)

IMP RULE: more than one statement in the function we use block plus
sometimes when we use return in the multiple statement

31/10/2023:

Arrays and methods:


===================

var arr=[1,2,3,34,4,5]

console.log(arr[0])

functions:
=============

function fn(param){}
function fn(param){
return something;
}
fn() - function call

anonymous function:

let get=function(param){
return something;
}

console.log(get)
console.log(get())

variable hoisting:
==================
po=90; console.log(po); var po; //hoisting
po1=90; console.log(po1); let po1; //let avoids hoisting

function hoisting:
===================

get1(); after 1000th line ---> function get1(){ console.log('hi')}

if used let , function hoisting is avoided

to make a function not to be hoisted we declare function as anonymous function ie store the
function in let or var

get2();

let get2=function()
{
console.log('hi')
}

arrow function:
==================

let get3=()=>console.log('hi')
get3()
let get4=()=>'hi welcome'
get4()

let add=(n1,n2)=> {
var res=n1+n2;
res=res-1
var final=res*2;
return final;
}
add(1,2)

let add=(n1,n2)=> n1+n2; //adds and returns the result automatically


add(1,2)

IMP RULE: more than one statement in the function we use block plus sometimes when we use
return in the multiple statement
nested function:

function outer(){
var out=90;
inner()
function inner()
{
var in1=800;
console.log('out variable is ',out);
console.log('inner variable is ',in1);
}
console.log('outer variable printed out is ',out);
console.log('inner variable printed out??? ',in1);
}

outer();

function outer(){

function inner()
{
console.log('inner');
}
inner()
console.log('outer');
}

outer();

pure function:
==============

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

add(2,3)//5
add(3,3)//6

impure ex:
===================
function getRandomInt(max) {
return Math.floor(Math.random() * max);
}
x=getRandomInt(90)//controls add function
function add(y){
return x+y;
}

add(3);//23
add(3);//47
add(3);//79

https://www.freecodecamp.org/news/what-is-a-pure-function-in-javascript-acb887375dfe/

higher order:
===============

function passed as input to another function

// let myfunc=()=>console.log('i am inner');

var myfunc=function()
{
console.log('i am inner');
}

function outer(fn)
{
console.log(fn);
}
outer(myfunc)

now we invoke the function passed:


-------------------------------------
function outer(fn)
{
console.log(fn);//not called
fn(); //executed or called
}
outer(myfunc)

currying:
============
var myfunc=function()
{
console.log('i am inner');
}
function outer(fn)
{
console.log('outer');
return fn;
}

//var fin=outer(myfunc);
//fin();

simplified as
outer(myfunc)();

callback eg method: filter, map......

var filterCondn=(x){
return x>5;
}
or
(x)=> x>5
or
var filterCondn= x=> x>5

var arr=[2,3,4,5,1,6,8,7]
arr.filter(filterCondn);
IMP:
======
A callback is a function that is passed as an argument to another function. what is a higher
order function? A higher order function is a function that takes at least one function as an input
and/or returns a function as an output.

Closure: later
===============

map()-
var mapCondn= x=> x*2
var arr=[2,3,4,5,1,6,8,7]
arr.map(mapCondn);

array -flat,, flatmap(),all,any,join , keys,entries,slice,splice,shif,value73


object - defineProperites,assign,create,freeze,bind,keys,values, some isXXXXX() methods
1-11-2023

Array - flat():
==================
const arr1 = [0, 1, 2, [3, 4]];

console.log(arr1.flat());
// expected output: Array [0, 1, 2, 3, 4]

const arr2 = [0, 1, [2, [3, [4, 5]]]];

console.log(arr2.flat());
// expected output: Array [0, 1, 2, Array [3, Array [4, 5]]]
console.log(arr2.flat(2));
// expected output: Array [0, 1, 2, 3, Array [4, 5]]
console.log(arr2.flat(Infinity));
// expected output: Array [0, 1, 2, 3, 4, 5]

includes:
const array1 = [1, 2, 3];

console.log(array1.includes(2));
// Expected output: true

const pets = ['cat', 'dog', 'bat'];

console.log(pets.includes('cat'));
// Expected output: true

console.log(pets.includes('at'));
some:
=====
const array = [1, 21, 31, 4, 5];

// Checks whether an element is even


const even = (element) => element % 2 === 0;

console.log(array.some(even));
// Expected output: true
--------------------------------------------------------
const array = [1, 21, 31, 41, 5];

// Checks whether an element is even


const even = (element) => element % 2 === 0;

console.log(array.some(even));
// Expected output: true

every():
=========
const isBelowThreshold = (currentValue) => currentValue < 40;

const array1 = [1, 230, 39, 29, 10, 13];

console.log(array1.every(isBelowThreshold));
// Expected output: true
--------------------------------------------------------
const isBelowThreshold = (currentValue) => currentValue < 40;

const array1 = [1, 30, 39, 29, 10, 13];

console.log(array1.every(isBelowThreshold));
// Expected output: true
includes(); - search logic, case sensitive

const array1 = [1, 2, 3];

console.log(array1.includes(2));
// Expected output: true

const pets = ['cat', 'dog', 'bat'];

console.log(pets.includes('cat'));
console.log(pets.includes('Cat'));
// Expected output: true

console.log(pets.includes('at'));

find():
==========
const array1 = [5, 789, 12, 8, 130, 44];

const found = array1.find((element) => element > 10);

console.log(found);

fill():
========
const array1 = [1, 2, 3, 4];

// Fill with 0 from position 2 until position 4


console.log(array1.fill(0, 2, 4));
// Expected output: Array [1, 2, 0, 0]

// Fill with 5 from position 1


console.log(array1.fill(5, 1));
// Expected output: Array [1, 5, 5, 5]

console.log(array1.fill(6));
// Expected output: Array [6, 6, 6, 6]

Object:
========

var obj={}

what is class name ob abv obj? Object

cosmic parent - Object

inheritence - __proto__, prototype

methods:

create():
=========
var obj={ name: 'ajay' }
undefined
var obj1=obj;
undefined
obj
{name: 'ajay'}
obj1
{name: 'ajay'}
obj1.name
'ajay'
obj.name
'ajay'
obj1.name='vinay' //changes the name in obj also
'vinay'
obj
{name: 'vinay'}
obj1
{name: 'vinay'}

obj and obj1 points to same memory,but changes will reflect in the parent
obj ...refer code above

var c1={ name:'ford', cap:24}


undefined
var c2=Object.create(c1)
undefined
c1
{name: 'ford', cap: 24}
c2
{}[[Prototype]]: Object
c1.name
'ford'
c1.cap
24
c2.name
'ford'
c2.cap
24
c2.cap=90 // //doesn't change cap in c1
90
c1
{name: 'ford', cap: 24}
c2
{cap: 90}
c1.cap
24
c2.cap
90

obj and obj1 points to same memory but changes will not reflect in the
parent obj

assign():

keys() & values():

const object1 = {
a: 'somestring',
b: 42,
c: false,
};
console.log(Object.keys(object1));
console.log(Object.values(object1));

Object.defineProperties()
Object.defineProperty()
Object.entries()
Object.freeze()

detructuring : array , object

array destructuring:

var arr=[689,87,67,9]

let [a,b]=arr;

skip values:
=============
var arr=[689,87,67,9]

let [e,,d]=arr;

2/11/2023

Object.hasOwn(obj_name,prop_name_to_be_Checked):

const object1 = {
a:89, b:67
};

Object.hasOwn(object1, 'prop')
false
Object.hasOwn(object1, 'a')
true
Object.hasOwn(object1, 'b')
true
Object.hasOwn(object1, 'c')
false

const object1 = {}; or const object1 = {a:8};

Object.defineProperty(object1, 'property1', {
value: 42,
writable: false,
});

console.log(object1.property1);

object1.property1=68
console.log(object1.property1);

change writable to true , will enable you to modify the value in object1

const object1 = {a:8};

Object.defineProperty(object1, 'a', {
value: 42,
writable: false,
});

console.log(object1.a);

object1.a=68
console.log(object1.a);

Object Destructuring:
=======================
let person = {
firstName: 'John',
lastName: 'Doe'
};

//prop name must be same while destructuring


let {firstName,lastName}=person;

let person = {
firstName: 'John',
lastName: 'Doe'
};

//prop name must be same while destructuring


let {firstName:fname,lastName}=person;
3/11/2023

NODE JS :
==========
Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine.

https://javascript.plainenglish.io/what-is-node-js-5fe50e4332c8

https://gitconnected.com/learn/node-js/nodejs-tutorial-for-beginners-73d764

In java - its blocking IO - its also single threaded but multi threads can be
created

System.out.println("hi");
Thread.sleep(3000);
System.out.println("hello");

in JS - non-blocking IO - its single threaded

console.log('hi');
setTimeout(()=>console.log('hello'),3000);
console.log('before');

https://www.javascripttutorial.net/javascript-event-loop/

https://scoutapm.com/blog/nodejs-architecture-and-12-best-practices-for-no
dejs-development
https://www.linkedin.com/pulse/nodejs-architecture-udara-abeythilake/

7/11/2023

const path = require('path');


// // console.log(path)
// console.log(path.sep)
// console.log(path.delimiter)

// The path.dirname()
// method returns the directory name of a specified path
// let result = path.dirname('/public_html/home/index.html');
// console.log(result);

// let result = path.dirname('/public_html/home/index'); //by default last


portion is taken as file name before portion as path or directory
// console.log(result);

// The path.extname() returns extension of the path. For example:

console.log(path.extname('index.html'));
console.log(path.extname('app.js'));
console.log(path.extname('node.js.md'));

// var extn = path.extname('index.html')


// if (extn === '.html')
// console.log('it is an html')
// else if (extn === '.j')
// console.log('it is an jss')
// else if (extn === '.js.md')
// console.log('it is an git file')

// let pathToFile = path.format({


// dir: 'public_html/home/js',
// base: 'app.js'
// });
// console.log(pathToFile)
let result = path.isAbsolute('C:\\node.js\\');
console.log(result); // true

result = path.isAbsolute('D:/node.js/');
console.log(result); // true

// result = path.isAbsolute('/public_html/dir1/');
// console.log(result); // true

// ./ means current folder where the file is present - so abov code is


true and it is
//treated as absolute path

result = path.isAbsolute('public_html/dir1/');
console.log(result); // false , if no / or c: or d: etc then its relative
path

//path.join() - task
// path.parse() - task

// path.normalize(path)
// path - '.','..'
var pathvar='c://dir//dir1//dir2//a.txt'
var pathvar1='c://dir//dir1//dir2//a.txt//..//..//b.txt'
console.log(path.normalize(pathvar1))
var pathvar2='c://dir//dir1//dir2//a.txt//..//..//..//b.txt'
console.log(path.normalize(pathvar2))

let pathToDir = path.normalize('C:\\node.js/module/js//dist');


console.log(pathToDir)

//path.relative()

In osmod.js
//os - operating system lib
var oslib=require('os')
// console.log(oslib)
// console.dir(oslib)

// console.log(oslib.cpus())
// console.log(oslib.cpus()[0].model)
// console.log(oslib.cpus()[11].times.user)

let currentOS = {
name: oslib.type(),
architecture: oslib.arch(),
platform: oslib.platform(),
release: oslib.release(),
version: oslib.version()
};

console.log(currentOS)
let totalMem = oslib.totalmem();
console.log(totalMem);
let freeMem = oslib.freemem();
console.log(freeMem);

/* task

const { model, speed } = os.cpus()[0];

console.log(`Model: ${model}`);
console.log(`Speed (MHz): ${speed}`);
*/

// task event driven programming - event model - task


//event listeners - task
//https://danielpuiatti.com/javascript-events-and-event-driven-programming
-a-comprehensive-guide/
8/11/2023

//events - core module -inbuilt

const EventEmitter = require('events');

// console.log(EventEmitter)

const event=new EventEmitter();


// function callMe(){
// console.log("I am called")
// }
// event.on('call',callMe) //listener created - 'call'

// function onButtonClick(){
// event.emit('call') // button event
// // event.emit('call') //possible
// // event.emit('call') //possible
// }
// onButtonClick()
// onButtonClick()
// onButtonClick()

// emit - 'explain nodejs'

// listen - u('explain nodejs') - takeNotes()

// function handleChange(){
// console.log("I ll get i/p from user each character")
// }
// event.on('onChange',handleChange) //listener created - 'call'

// function onButtonClick(){
// event.emit('onChange') // button event
// // event.emit('call') //possible
// // event.emit('call') //possible
// }
// handleChange()
// handleChange()
// handleChange()
// handleChange()

//event has to listen only once

function handleChange(){
console.log("I ll get i/p from user each character")
}

event.once('onChange',handleChange) //listener created - 'call'

function onButtonClick(){
event.emit('onChange') // button event
event.emit('onChange') //possible
event.emit('onChange') //possible
}
onButtonClick()//like OTPs
//auto detach (ie) eventlistener gets deleted

// detach lister - task

9/11/2023
const fs=require('fs')

//console.log(fs)

//r Open file for reading. An exception occurs if the file does not exist.
// //by default it takes 'r' mode/flag
// fs.readFile('TestFile.txt', function (err, data) {
// if (err)
// //throw err;//will be thrown to javascript engine (js VM) /node
engine
// console.log(err)
// console.log(data);
// });
//open file for read with r+ mode/flag
// for api docs -
https://nodejs.org/docs/latest-v18.x/api/documentation.html
// fs.readFile('TestFile.txt',{flag:'r+'},function (err, data) {
// if (err)
// //throw err;//will be thrown to javascript engine (js VM) /node
engine
// console.log(err)
// console.log(data);
// });

//writing file in async way

// fs.writeFile('TestFile.txt','hi hello',function (err) {


// if (err)
// //throw err;//will be thrown to javascript engine (js VM) /node
engine
// console.log(err)
// });

//if file already existing-file is truncated


// fs.writeFile('TestFile.txt','where are you',function (err) {
// if (err)
// //throw err;//will be thrown to javascript engine (js VM) /node
engine
// console.log(err)
// });

//wx - file already exist error


// fs.writeFile('TestFile1.txt','new content',{flag:'wx'},function (err) {
// if (err)
// //throw err;//will be thrown to javascript engine (js VM) /node
engine
// console.log(err)
// });

// fs.writeFile('TestFile2.txt','\n content to append',{flag:'a'},function


(err) {
// if (err)
// //throw err;//will be thrown to javascript engine (js VM)
/node engine
// console.log(err)
// });
fs.open('TestFile3.txt', 'r', function (err, fd) {

if (err) {
console.error(err);
}

});

//buffer- Buffer
// function callback(err){
// if(err)
// console.log("Error Occurred :: ",err);
// else
// console.log('renamed...')
// }
//fs.rename('new_text.txt', 'new_text1.txt', callback)

// function callback(exist,err){
// //err wont work here. it will be null always. no err will be thrown
// if(!exist)
// {
// console.log("Exist??? ",exist);
// console.log(err)
// }
// else
// console.log('renamed...')
// }
// fs.exists('new_text.txt', callback)

//1. if file exists , read and display content


//2. only if exists , delete
//3. only if exists , rename the file
// function callback(err){
// console.log(err)
// }
// fs.mkdir('C:\\Users\\kathiresann\\Desktop\\New folder\\dir1', callback)

// function callback(err){
// console.log(err)
// }
// fs.mkdir('C:\\Users\\kathiresann\\Desktop\\New folder\\dir1\\dir2',
callback)

// dir1 doesn't exist, so dir2 cannot be createed without it because by


default
// path will point only to or path will consider last section mainly
//so solution is

// function callback(err){
// console.log(err)
// }
// fs.mkdir('C:\\Users\\kathiresann\\Desktop\\New folder\\dir1\\dir2',
callback)

// recursive property indicating whether parent directories should be


created.
//where to specify this prop?

// function callback(err){
// console.log(err)
// }
// fs.mkdir('C:\\Users\\kathiresann\\Desktop\\New
folder\\dir\\dir1\\dir2',{recursive:true}, callback)

// //fs.rmdir(path, callback) - task


// //fs.stat(path, callback) - task

function callback(err){
console.log(err)
}
// fs.copyFile('source.txt', 'copy_loc\\destination.txt',callback);
//rule1: src name and destnation name must be same
// fs.copyFile('source.txt', 'copy_loc\\source.txt',callback);
//rule2: if file in dest folder already exist??
//fs.copyFile('source.txt',
'copy_loc\\source.txt',fs.constants.COPYFILE_EXCL,callback);
//additional modes
//fs.constants.COPYFILE_FICLONE:
//fs.constants.COPYFILE_FICLONE_FORCE:

// open file with read, write and append mode -fs.open() task

15/11/2023

//obj stored in heap mem(v8-JS vm)/JS engine


//number, str,{},symbol,null,undefined etc

//buffer stores info outside v8 engine (ie outside heap)

// Buffer - class (B sgud be upper case as it is a global class)


//since global , no need to import using require/import

// var buf=new Buffer(10);//pass size of the buffer


//@deprecated — since v10.0.0 - Use Buffer.alloc() instead (also see
Buffer.allocUnsafe()).
//console.dir(buf)

//var buf1=Buffer.alloc(10);
// var buf1=Buffer.alloc(10,90); //fills by zero by default if sec arg not
given
// console.dir(buf1)
// console.time('buf check');
// var arr=[1,2,4,5,7,6,7,8]
// var buf=new Buffer(arr);
// console.log(buf)
// console.log('length of buffer is ',buf.length)
// console.log(buf.at(3))
// console.log(buf.includes(9))
// console.timeEnd('buf check');
// console.timeLog('buf check');
// //passing strings to buffer
// var buf2=new Buffer('hi hello');
// console.time('simple');
// console.log(buf2)
// console.timeEnd('simple')
// console.timeLog('simple')

// var buf3=new Buffer(10,20); //sec arg wont work


// console.log(buf3)
//https://www.rapidtables.com/convert/number/hex-to-decimal.html
// var buf3=Buffer.from() - task
// var buf4=Buffer.of() - task

// read a file and store it in a buffer and print it,


// buffer should be iterated by for loop - task

var buf4=new Buffer(10);


console.log(buf4)
buf4.write('hi')
console.log(buf4) //will it overwrite/replace on h and i char or append
buf4.write('hello')
console.log(buf4) //hi is replaced bu hello, its not appended
//buf4.join() - task
//buf4.toString(); - task

16/11/2023

var buf1 = Buffer.from('x');


var buf2 = Buffer.from('y');
var a = Buffer.compare(buf1, buf2);

//This will return -1


console.log(a);

var buf1 = Buffer.from('y');


var buf2 = Buffer.from('x');
var a = Buffer.compare(buf1, buf2);
//This will return 1
console.log(a);

// Buffer.concat()
// Just like string concatenation, you can join two or more buffer
objects into one object. You can also get the length of the new
object:

var buffer1 = Buffer.from('x');


var buffer2 = Buffer.from('y');
var buffer3 = Buffer.from('z');
var arr = [buffer1, buffer2, buffer3];

/*This will print buffer, !concat [ <Buffer 78>, <Buffer 79>, <Buffer
7a> ]*/
console.log(arr);

//concatenate buffer with Buffer.concat method


var buf = Buffer.concat(arr);

//This will print <Buffer 78 79 7a> concat successful


console.log(buf);

//Buffer.fill()
const b = Buffer.alloc(10).fill('a');
console.log(b.toString());

// Buffer.from()
//The buffer.from() method enables you to create a new buffer
from any object,
// like strings, buffer, arrays, and ArrayBuffer()
// Create a buffer from a string
var mybuff = Buffer.from("Nigeria");
//Print Buffer Created
console.log(mybuff);

// Create a buffer from a buffer


// Create buffer from string
var mybuff = Buffer.from("Nigeria");
// Create buffer from the first buffer created
var buff = Buffer.from(mybuff);
// Print out final buffer created.
console.log(buff);

// create a buffer from an array


const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]);

// Create a buffer from an arraybuffer


const ab = new ArrayBuffer(10);
// Specify offset and length
const buf = Buffer.from(ab, 0, 2);
console.log(buff);

//buff.includes()
// The method returns a boolean true or false depending on
whether a value is found:
const buf = Buffer.from('this is a buffer');
console.log(buf.includes('this'));
// This will print true
console.log(buf.includes(Buffer.from('a buffer example')));
// This will print false

Buffer.isEncoding()
//To tell binaries apart, they must be encoded.
//You can use the Buffer.isEncoding() method to confirm whether
a particular character
// encoding type is supported:

console.log(Buffer.isEncoding('hex'));
// This will print true

console.log(Buffer.isEncoding('utf-8'));
// This will print true

console.log(Buffer.isEncoding('utf/8'));
// This will print false

console.log(Buffer.isEncoding('hey'));
// This will print false

// buf.json()
// The buf.json() method returns a JSON version of the buffer
object:

const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);

console.log(buf.toJSON());
// This will print {"type":"Buffer", data:[1,2,3,4,5,6,7,8]}

//ADDITIONAL READS
//https://www.freecodecamp.org/news/do-you-want-a-better-unde
rstanding-of-buffer-in-node-js-check-this-out-2e29de2968e8/

// Buffer.compare()

// The Buffer.compare() method enables you to compare two buffer objects


to check whether
// they are equal. This method returns -1, 0, or 1, depending on the
result of the
// // comparison.
// var buf1 = Buffer.from('xyz');
// var buf2 = Buffer.from('xyz');
// var a = Buffer.compare(buf1, buf2);

// //This will return 0


// console.log(a);

// Buffer.concat()
// Just like string concatenation, you can join two or more buffer objects
into one object. You can also get the length of the new object:

// var buffer1 = Buffer.from('x');


// var buffer2 = Buffer.from('y');
// var buffer3 = Buffer.from('z');
// var arr = [buffer1, buffer2, buffer3];

// /*This will print buffer, !concat [ <Buffer 78>, <Buffer 79>, <Buffer
7a> ]*/
// console.log(arr);

// //concatenate buffer with Buffer.concat method


// var buf = Buffer.concat(arr);

//This will print <Buffer 78 79 7a> concat successful


// console.log(buf);

// const buf = Buffer.from([0x41, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);
// console.log(buf.toJSON());

// const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex');

// const buf2 = Buffer.from('hi');


// console.log(buf2)

// read a image and write a image with help of buffer - TASK

const buf2 = Buffer.from([67,68]);


console.log(buf2.toString())
console.log(buf2.toString("hex"))
console.log(buf2.toString("base64"))

var http=require('http')
const server = http.createServer((req, res) => {
console.log(req.url)
if (req.url === '/') {
res.write('<h1>Hello, Node.js!</h1>');
}
else if(req.url==='/hi'){
res.write('<h1>Welcome, USER!</h1>');
}
res.end();
});
server.listen(4000);
console.log(`The HTTP Server is running on port 4000`);

var http=require('http')
const server1 = http.createServer((req, res) => {
console.log(req.url)

if (req.url === '/') {


res.write('<html><head><title>My Calc</title></head>');
res.write('<body><h1>This is a simple calculator</h1>');
res.write("<a href='add'>Add</a> <br/>");
res.write("<a href='sub'>Sub</a> </body></html>");
}
else if(req.url==='/add'){
res.write('<h1>Addition</h1>');
}
else if(req.url==='/sub'){
res.write('<h1>Subraction</h1>');
}
res.end();
});
server1.listen(4000);
console.log(`The HTTP Server is running on port 4000`);

//index.html file with some content(anything) - assume this is my home


page
//when the req is /(slash) - display this html file to user
//hint use path module, fs mod, etc

//small files
//sync also async
//complete file is loaded into memory
// fs.readFile('C:\\Users\\kathiresann\\Desktop\\clay.png', readData);

// hello - h8e8l8l8o8 - myutf8 - hello

// ReadStream - loads file by chunks(pieces)


//its only async

var fs = require("fs");
function readData(err, data) {
if(err)
console.log(err);

console.log(data);
fs.writeFile('c.png',data,(err)=>console.log(err))

}
//small files
//sync also async
//complete file is loaded into memory
fs.readFile('C:\\Users\\kathiresann\\Desktop\\clay.png','base64',
readData);

// hello - myutf8 -h8e8l8l8o8 - b4- h84e84l84l84o84 - file gets corrupted


//readStream + writeSTream
//pipe

//server program - ours


//can have any number of server program running on node js (runtime env)
//two server prog or application cannot run in same port number - error
//each program will have to listen to their own port number for incoming
req

var http=require('http')
const server = http.createServer((req, res) => {
console.log(req.url)
if (req.url === '/') // what operation to be perform
{
res.write('<h1>Hello, Node.js!</h1>');
}
else if(req.url==='/hi'){
res.write('<h1>Welcome, USER!</h1>');
}
res.end();
});
server.listen(4000);
console.log(`The HTTP Server is running on port 4000`);
var http=require('http')
const server1 = http.createServer((req, res) => {
console.log(req.url)
if (req.url === '/') {
res.write('<h1>Hello, Node.js!-server2</h1>');
}
else if(req.url==='/hi'){
res.write('<h1>Welcome, USER! -server2</h1>');
}
res.end();
});
server1.listen(4000);
console.log(`The HTTP Server is running on port 4000`);
//change port number to RESOLVE error

20-11-2023
var http = require('http');
var url = require('url');

const server=http.createServer(function (req, res) {


res.writeHead(200, {'Content-Type': 'text/html'});
var q = url.parse(req.url, true).query;
console.log(req.url)

var txt = q.year + " " + q.month;


txt=txt+" "+q.m
txt="<h1>"+txt+"<h1>"
console.log(q)
res.end(txt);

})
const PORT = 8085;
server.listen(PORT, () => {
console.log(`Server is running at http://localhost:${PORT}/`);
});

//http://localhost:8085/?year=2023&m=11
//query parameters will be after ? symbol
// here m iss not matching to key given in code , use same key to
destructure(in line 6&7)

To display an HTML file from a public folder using Node.js, you


can create a simple web server using the http and fs modules.
Here's a basic example:

First, make sure you have Node.js installed on your machine.

Create a folder for your project and navigate to it in the terminal.

Create an index.js file for your Node.js server.


Create a public folder in the same directory as index.js and place
your HTML file (let's say index.html) inside it.

Now, in your index.js file, you can use the following code:

const http = require('http');


const fs = require('fs');
const path = require('path');

const server = http.createServer((req, res) => {


// Set the content type to HTML
res.setHeader('Content-Type', 'text/html');

// Read the HTML file from the public folder


const filePath = path.join(__dirname, 'public', 'index.html');

// Check if the file exists & access


fs.access(filePath, fs.constants.R_OK, (err) => {
if (err) {
// If the file doesn't exist, return a 404 response
res.statusCode = 404;
res.end('File not found');
} else {
// If the file exists, read and send its content
fs.createReadStream(filePath).pipe(res);
}
});
});

const PORT = 3000;


server.listen(PORT, () => {
console.log(`Server is running at http://localhost:${PORT}/`);
});
Save the file and run it using the command node index.js.

Open your browser and navigate to http://localhost:3000/ to see


your HTML file.

This example assumes that your HTML file is named index.html


and is located in the public folder.

fs: This refers to the Node.js file system module.


constants: This is an object within the fs module that contains
various constants related to file system operations.
R_OK: This specific constant represents the permission to read
the file. If a file or directory has read permission, the fs.access
method with fs.constants.R_OK will succeed, indicating that the
file is readable.
So, in the code example provided earlier, fs.access(filePath,
fs.constants.R_OK, (err) => {...}) is checking whether the file
specified by filePath is readable. If it is, the code proceeds to
read and send its content; otherwise, it returns a 404 response
indicating that the file is not found or not readable.

use only http mod:


https://web.skype.com/?action=joinmeetnow&correlationId=c114
b114-4f5d-458a-a9c6-abc4b057d39a&source=NewJoinLinkFlow
req.url - we cant extract k-v pairs seperately

easy solution - url lib

//FOR VALIDATION
//with express
//https://medium.com/@techsuneel99/validate-incoming-requests-in-node-js-l
ike-a-pro-95fbdff4bc07#:~:text=Server%2Dside%20validation%3A%20Server%2D,c
lient%2Dside%20validation%20may%20miss.

const http = require('http');


const fs = require('fs');
const path = require('path');

const server = http.createServer((req, res) => {


console.log(req)
console.log(req.statusCode)
console.log(res)

// Set the content type to HTML


// res.setHeader('Content-Type', 'text/html');
// res.writeHead(200, {'Content-Type': 'text/plain'});
res.writeHead(404, {'Content-Type': 'text/plain'}); //wwrong cause msg
and code doesn't match but page getss displayed- logically wrong
// Read the HTML file from the public folder
const filePath = path.join(__dirname, 'public', 'index.html');
//__dirname = current folder hierarchy
//eg: ass of now the file is in = D:\nodejs\nodeb2\
console.log( filePath)
// Check if the file exists & access
fs.access(filePath, fs.constants.R_OK, (err) => {
if (err) {
// If the file doesn't exist, return a 404 response
res.statusCode = 404; //by default 404 's msg
res.end('File not found'); //customized err msg to print to user
//res.end()
} else {
// If the file exists, read and send its content
fs.createReadStream(filePath).pipe(res);
}
console.log(res.statusCode)
});
});

const PORT = 3000;

server.listen(PORT, () => {
console.log(`Server is running at http://localhost:${PORT}/`);
});

23/11/2023
var http = require('http');
var formidable = require('formidable');
var path=require('path')
var fs=require('fs')
http.createServer(function (req, res) {
if (req.url == '/fileupload') {
var form = new formidable.IncomingForm();
form.parse(req, (err, fields, files) => {
if (err) {
console.error('Error parsing form:', err);
res.writeHead(500, {'Content-Type': 'text/plain'});
res.end('Internal Server Error');
return;
}

const oldPath =
files.filetoupload[0].filepath//files.filetoupload.path;
console.log(files.filetoupload[0].filepath)
const newPath = __dirname + '/images/'
+files.filetoupload[0].originalFilename;

fs.copyFile(oldPath, newPath, (err) => {


if (err) {
console.error('Error moving file:', err);
res.writeHead(500, {'Content-Type': 'text/plain'});
res.end('Internal Server Error');
} else {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('File uploaded and moved!');
}
});
});

} else {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('<form action="fileupload" method="post"
enctype="multipart/form-data">');
res.write('<input type="file" name="filetoupload"><br>');
res.write('<input type="submit">');
res.write('</form>');
return res.end();
}
}).listen(8085,()=>console.log("app is running in 8085"));

24-11-2023

const http = require('http');


const url = require('url');
const fs = require('fs');
const path = require('path');

const dataFilePath = path.join(__dirname, 'data.json');

// Read existing data from file or initialize an empty array


let data = [];
if (fs.existsSync(dataFilePath)) {
const dataFileContent = fs.readFileSync(dataFilePath, 'utf8');
data = JSON.parse(dataFileContent);
}

const server = http.createServer((req, res) => {


const reqUrl = url.parse(req.url, true);
console.log(reqUrl)
if(reqUrl.pathname==='/' && req.method === 'GET'){
res.writeHead(200, { 'Content-Type': 'text/html'});
//if u need to cut short resp dynamically based on condition , use
content-length
//res.writeHead(200, { 'Content-Type': 'text/html','content-length':30
});
res.write("<a href='get-data'>click to see all data</a>")
res.end();//committed - displayed to user
return;
}
else if (reqUrl.pathname === '/get-data' && req.method === 'GET') {
// Read operation
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(data));

//get by id - TASK
//based on form - get id from form using query module and
search against
//data var (json array from file)
//res.end or res.send() - return resp
}
else if (reqUrl.pathname === '/add-data' && req.method === 'POST') {
// Create operation
let body = '';
req.on('data', (chunk) => {
body += chunk;
});

req.on('end', () => {
const newData = JSON.parse(body);
data.push(newData);
saveDataToFile();
res.writeHead(201, { 'Content-Type': 'text/plain' });
res.end('Data added successfully');
});
}
else if (reqUrl.pathname === '/update-data' && req.method ===
'PUT') {
// Update operation
let body = '';
req.on('data', (chunk) => {
body += chunk;
});

req.on('end', () => {
const updatedData = JSON.parse(body);
const indexToUpdate = data.findIndex((item) => item.id ===
updatedData.id);

if (indexToUpdate !== -1) {


data[indexToUpdate] = updatedData;
saveDataToFile();
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Data updated successfully');
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Data not found');
}
});

} else if (reqUrl.pathname === '/delete-data' && req.method ===


'DELETE') {
// Delete operation
let body = '';
req.on('data', (chunk) => {
body += chunk;
});

req.on('end', () => {
const idToDelete = JSON.parse(body).id;
const newData = data.filter((item) => item.id !==
idToDelete);

if (newData.length < data.length) {


data = newData;
saveDataToFile();
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Data deleted successfully');
}
});
}
});

const saveDataToFile = () => {


fs.writeFileSync(dataFilePath, JSON.stringify(data), 'utf8');
};

const PORT = 3000;


server.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});

CRUD -
C - Create a record
R - Read the record
U - Update the record
D - Delete the record

data can be in DB or Json Mock server or Json local file

http -

client - server

Browser to Server application - req header (automatically send in


all req user makes to the app)
Server Application to Browser - resp header (it can unsderstood
as dev giving hints to browser to do something. like page-refresh
or cookie to get deleted after specific time

HTTP methods to be used:


===========================
create - POST (non-idompotent)
read one record or all - get
delete one record - delete
update one record - put,patch - instead if application huge - use
delete+post(improves performnace)

process -

mysql -

express + node

29/11/2023
—-------------
const mysql = require('mysql'); //driver
console.log(mysql)
//3 -node mem - GC
const con = mysql.createConnection({
host: 'localhost', //url
user: 'root',
password: 'clayfin@123',
database: 'mydb'
});
//console.log(con) //config
//err is given by node engine/server
// con.connect((err) => {
// if(err){
// console.log(err.toString());
// console.log('Error connecting to Db');
// return;
// }
// console.log('Connection established');
// });

// con.connect((err) => {
// if(err){
// console.log(err.toString());
// //console.log('Error connecting to Db');
// return;
// }
// console.log('Connection established');
// });

//reading
// const con = mysql.createConnection({
// host: 'localhost',
// user: 'root',
// password: 'password',
// database: 'mydb'
// });
//connection gets auto established by query()
// con.query('SELECT * FROM books', (err,rows) => {
// if(err) throw err;

// console.log('Data received from Db:');


// console.log(rows);
// //to print row by row
// rows.forEach( (row) => {
// console.log(`${row.id} for - ${row.title} - ${row.author}`);
// });
// });
// con.end((err) => {
// if(err)
// console.log('error happened',err)
// });
//getbyid
// const con = mysql.createConnection({
// host: 'localhost',
// user: 'root',
// password: 'password',
// database: 'mydb'
// });
// let id=1005;
// con.query(`SELECT * FROM books where id=${id}`, (err,rows) => {
// if(err) throw err;

// console.log('Data received from Db:');


// console.log(rows); //its in array , used forEach instead of rows[0]
// //to print row by row
// rows.forEach( (row) => {
// console.log(`${row.id} of ${row.title} ${row.author}`);
// });
// });
// con.end((err) => {
// if(err)
// console.log('error happened',err)
// });
// inserting record:
// const con = mysql.createConnection({
// host: 'localhost',
// user: 'root',
// password: 'password',
// database: 'mydb'
// });
// const i=Number(prompt('enetr id'))
const book = { id:1008, title:'reactjs flux',author: 'Alex' };
con.query('INSERT INTO books SET ?', book, (err, res) => {
if(err) throw err; //err to the node engine and prog stops
console.log('result is ', res);
console.log('Last insert ID:', res.insertId);
});
con.end((err) => {
if(err)
console.log('error happened',err)
});
// con.query('SELECT * FROM authors', (err,rows) => {
// if(err) throw err;

// console.log('Data received from Db:');


// console.log(rows);
// //to print row by row
// rows.forEach( (row) => {
// console.log(`${row.name} lives in ${row.city}`);
// });
// });
// con.end((err) => {
// if(err)
// console.log('error')
// });
//updating
/*const con = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'mydb'
});
con.query(
'UPDATE authors SET city = ? where id=?',
['UK', 10],
(err, result) => {
if (err) throw err;
console.log(result)
console.log(`Changed ${result.changedRows} row(s)`);
console.log(`affected ${result.affectedRows} row(s)`);//counts every
time u run update
}
);
con.query('SELECT * FROM authors', (err,rows) => {
if(err) throw err;

console.log('Data received from Db:');


console.log(rows);
//to print row by row
rows.forEach( (row) => {
console.log(`${row.name} lives in ${row.city}`);
});
});
con.end((err) => {
if(err)
console.log('error')
});
*/

con.query(
// 'UPDATE books SET price= ?, qty=? where id=?',
// [100, 10, 1008],
// (err, result) => {
// if (err) throw err;
// console.log(result)
// console.log(`Changed ${result.changedRows} row(s)`);
// console.log(`affected ${result.affectedRows} row(s)`);//counts
every time u run update
// }
// );
// con.query('SELECT * FROM books', (err,rows) => {
// if(err) throw err;

// console.log('Data received from Db:');


// console.log(rows);
// //to print row by row
// rows.forEach( (row) => {
// console.log(`${row.id} author in ${row.author} price
${row.price} qty ${row.qty}`);
// });
// });
// con.end((err) => {
// if(err)
// console.log('error')
// });

You might also like