Node Js Notes
Node Js Notes
JS - ES5
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
Javascript:
============
datatype -
loosely typed
var -
10
hi hello
4.5
true
A
var a=90;
a='hi'
a=true
27/10/2023
Javascript:
=============
datatypes
scopes :
visibility
function scope
global scope
local scope - ES6
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
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:
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)
}
===============================
default parameter:
===================
function say(message) {
console.log(message);
}
//message - parameter
s="hello"
say(s) // s- argument
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
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
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`
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:
===================
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)
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:
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:
===================
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)
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:
===============
var myfunc=function()
{
console.log('i am inner');
}
function outer(fn)
{
console.log(fn);
}
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)();
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():
==================
const arr1 = [0, 1, 2, [3, 4]];
console.log(arr1.flat());
// expected output: Array [0, 1, 2, 3, 4]
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
console.log(pets.includes('cat'));
// Expected output: true
console.log(pets.includes('at'));
some:
=====
const array = [1, 21, 31, 4, 5];
console.log(array.some(even));
// Expected output: true
--------------------------------------------------------
const array = [1, 21, 31, 41, 5];
console.log(array.some(even));
// Expected output: true
every():
=========
const isBelowThreshold = (currentValue) => currentValue < 40;
console.log(array1.every(isBelowThreshold));
// Expected output: true
--------------------------------------------------------
const isBelowThreshold = (currentValue) => currentValue < 40;
console.log(array1.every(isBelowThreshold));
// Expected output: true
includes(); - search logic, case sensitive
console.log(array1.includes(2));
// Expected output: true
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];
console.log(found);
fill():
========
const array1 = [1, 2, 3, 4];
console.log(array1.fill(6));
// Expected output: Array [6, 6, 6, 6]
Object:
========
var obj={}
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
obj and obj1 points to same memory but changes will not reflect in the
parent obj
assign():
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()
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
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
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'
};
let person = {
firstName: 'John',
lastName: 'Doe'
};
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");
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
// The path.dirname()
// method returns the directory name of a specified path
// let result = path.dirname('/public_html/home/index.html');
// console.log(result);
console.log(path.extname('index.html'));
console.log(path.extname('app.js'));
console.log(path.extname('node.js.md'));
result = path.isAbsolute('D:/node.js/');
console.log(result); // true
// result = path.isAbsolute('/public_html/dir1/');
// console.log(result); // true
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))
//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
console.log(`Model: ${model}`);
console.log(`Speed (MHz): ${speed}`);
*/
// console.log(EventEmitter)
// function onButtonClick(){
// event.emit('call') // button event
// // event.emit('call') //possible
// // event.emit('call') //possible
// }
// onButtonClick()
// onButtonClick()
// onButtonClick()
// 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()
function handleChange(){
console.log("I ll get i/p from user each character")
}
function onButtonClick(){
event.emit('onChange') // button event
event.emit('onChange') //possible
event.emit('onChange') //possible
}
onButtonClick()//like OTPs
//auto detach (ie) eventlistener gets deleted
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);
// });
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)
// function callback(err){
// console.log(err)
// }
// fs.mkdir('C:\\Users\\kathiresann\\Desktop\\New folder\\dir1\\dir2',
callback)
// function callback(err){
// console.log(err)
// }
// fs.mkdir('C:\\Users\\kathiresann\\Desktop\\New folder\\dir1\\dir2',
callback)
// function callback(err){
// console.log(err)
// }
// fs.mkdir('C:\\Users\\kathiresann\\Desktop\\New
folder\\dir\\dir1\\dir2',{recursive:true}, callback)
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
//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')
16/11/2023
// 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:
/*This will print buffer, !concat [ <Buffer 78>, <Buffer 79>, <Buffer
7a> ]*/
console.log(arr);
//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);
//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()
// 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:
// /*This will print buffer, !concat [ <Buffer 78>, <Buffer 79>, <Buffer
7a> ]*/
// console.log(arr);
// const buf = Buffer.from([0x41, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);
// console.log(buf.toJSON());
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)
//small files
//sync also async
//complete file is loaded into memory
// fs.readFile('C:\\Users\\kathiresann\\Desktop\\clay.png', readData);
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);
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 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)
Now, in your index.js file, you can use the following code:
//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.
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;
} 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
//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);
req.on('end', () => {
const idToDelete = JSON.parse(body).id;
const newData = data.filter((item) => item.id !==
idToDelete);
CRUD -
C - Create a record
R - Read the record
U - Update the record
D - Delete the record
http -
client - server
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;
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;