Java Script CWH-- HTML-CSS Part section
Java Script CWH-- HTML-CSS Part section
Hamburger Icon or Menu in mobile view sites
JS -
Writing in-browser JavaScript and Developer Console | Web Development Tutorials #47
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Java Script Tutorial</title>
</head>
<body>
<div class="container">
<div class="row">
<p>
This is a row in this container
</p>
</div>
</div>
<script>
// Write JS code here
console.log('Hello World')
</script>
</body>
</html>
Variables, Data Types and Operators in JavaScript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Variable Data type</title>
<script>
let a = 78;
var b = "Harry";
c = 34.55;
//console.log(c)
//Operators in Javascript
//Operand - entities on which operators operate
// In 3 + 4 "+" is the operator and 3,4 are operands
// 1. unary operator - It has single operands (x= -x)
c = -c;
//console.log(c)
// 2. binary operator -
c = 456+8;
//console.log(c);
var num1 = 2;
var num2 = 9;
//Arithmatic Operations
console.log("The value of num1 + num2 is "+ (num1 + num2));
console.log("The value of num1 - num2 is "+ (num1 - num2));
console.log("The value of num1 * num2 is "+ (num1 * num2));
console.log("The value of num1 / num2 is "+ (num1 / num2));
console.log("The value of num1 ** num2 is "+ (num1 ** num2));
console.log("The value of num1 ++ is "+ (num1 ++));
console.log("The value of num1 ++ num2 is "+ (++num1));
console.log("The value of num1 -- is "+ (num1--));
console.log("The value of num1 -- is "+ (--num1));
</script>
</head>
<body>
<div class="container">
<h1>This is a heading</h1>
<div class="content">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Accusantium officia praesentium iste rem maxime deleniti quisquam suscipit quam aperiam. Ullam laboriosam amet eligendi laudantium et, quisquam velit earum porro illo sequi iusto expedita aliquid? Numquam, cum corrupti.
</div>
</div>
</body>
</html>
Strings in JavaScript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Javascript | String and String Method </title>
</head>
<body>
<div class="container">
<h1>This is heading</h1>
<div id="content"></div>
<p>
Lorem ipsum dolor, sit amet consectetur adipisicing elit. Illo quas harum consequuntur voluptatibus quasi officiis cupiditate omnis vero numquam culpa delectus esse quaerat, nihil provident quia veritatis nisi voluptas modi! <br><br>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Non at tempore, nihil laudantium suscipit officiis commodi! Dolore molestiae cupiditate earum odit similique rem laudantium? Quisquam dicta nulla enim quasi ut quibusdam aspernatur, iste fuga minima explicabo magnam libero quod sit perferendis officiis voluptatum nesciunt odit cum eum laborum laboriosam nihil! Quod quidem id aspernatur modi!
</p>
</div>
<script>
//var string = "this";
var string = 'thi"s';
var name = 'Sameer';
var channel = 'Samer Creative Channel';
var message = 'Samer is good boy';
var temp = `${name} is a 'nice' person and he "has" a channel called ${channel}`;
//console.log(string + name + message + channel);
//console.log(temp);
//var len = name.length;
//console.log(`Length of name is ${len}`)
//console.log("Hello world\nSameer\tand")
var y = new String("this");
console.log(y);
document.getElementById('content').innerHTML = '<h3> this is an h3 heading </h3>'
</script>
</body>
</html>
String Functions in JavaScript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title> JavaScript String Functions </title>
<style>
</style>
</head>
<body>
<script>
var str = "This is a string";
console.log(str);
//First occurence of a substring
var position = str.indexOf('is');
console.log(position)
//Last occurence of a substring
position = str.lastIndexOf('is');
console.log(position)
//Substring from a string
//var substr = str.slice(1,7); (could take negative number)
//var substr = str.substring(1,7);
var substr1= str.substr(1,3 );
console.log(substr1)
//var replaced = str.replace('string', 'Harry');
//console.log(str)
//console.log(replaced)
//console.log(str.toUpperCase());
//console.log(str.toLowerCase());
// var newString = str.concat('New String')
// console.log(newString)
// var strWithWhitespaces = " this contains whitespace ";
// console.log(strWithWhitespaces)
// console.log(strWithWhitespaces.trim())
// var char2 = str.charAt(2);
// var char2 = str.charCodeAt(2); // Not very important
console.log(str[6])
</script>
</body>
</html>
Scope, If-else Conditionals & Switch Case in JavaScript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Scope, If-else Conditionals & Switch Case in JavaScript</title>
</head>
<body>
<div>
<ul>
<li>Item-1</li>
<li>Item-2</li>
<li>Item-3</li>
<li>Item-4</li>
<li>Item-5</li>
<li>Item-6</li>
<li>Item-7</li>
</ul>
</div>
<script>
// var string1 = "This is a string"
// var string1 = "This is a string2"
// console.log(string1);
// let a = "u" ;
// {
// let a = "u26"; Local variable, need to use let for javascript
// console.log(a)
// }
// console.log(a)
// const a = "This is cannot be changed";
// a = "I want to change this. This cannot be changed";
// console.log(a);
// let age = 5;
// if (age>=18){
// console.log("You can drink water");
// }
// else if (age==2){
// console.log("Age is 2");
// }
// else if (age==5){
// console.log("Age is 6");
// }
// else{
// console.log("You can drik Cold Drink");
// }
const cups = 43
switch (cups) {
case 4:
console.log("The value of cups is 4")
// break;
case 41:
console.log("The value of cups is 41")
// break;
case 42:
console.log("The value of cups is 42")
// break;
case 43:
console.log("The value of cups is 43")
// break;
default:
console.log("The value of cups is none of 4, 41, 43")
// break; if break not use then after that all value will print
}
</script>
</body>
</html>
Arrays & Objects in JavaScript
Arrays & Objects in JavaScript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Arrays & Objects in JavaScript</title>
</head>
<body>
<div class="container">simple si HTML</div>
<script>
let myVar = 34;
let myVar2 = "string";
let myVar3 = true;
let myVar4 = null;
let myVar5 = undefined;
//Below are custom object , key valure pairs
// let employee = {
// name: "Sameer",
// salary: 10,
// channel: "codewithsamer",
// channel2: "programmingwithsameer2"
// }
// console.log(employee);
// Object Orineted
// let name = [1, 2, 4, "Samer", undefined];
// let name = new Array(1, 2, 4, "Harry", undefined);
let name = new Array(25); // Empty declaration
console.log(name.length);
name = name.sort(); //For sorting the elements
name.push("this is pushed")
console.log(name);
</script>
</body>
</html>
Functions in JavaScript
console.log("this is tuurioal 53");
function greet(name, greetText= "Greting from JavaScript"){
console.log(greetText + " "+ name);
console.log(name + " is a good boy");
}
function sum(a,b,c){
let d = (a+b+c);
return d;
//This line will never execute
//console.log("Function is returned")
}
let name ="Harry";
let name1 = "Shubham";
let name2 = "Rohan";
let name3 = "Sagar";
let greetText = "Good Morning";
// Below are function calling
greet(name,greetText);
greet(name1,greetText);
greet(name2,greetText);
greet(name3); //This wil take the default value
let returnVal = sum (1,2,3);
console.log(returnVal)
// console.log(name + " is a good boy");
// console.log(name1 + " is a good boy");
// console.log(name2 + " is a good boy");
// console.log(name3 + " is a good boy");
JavaScript Tutorial: Interaction - Alert, Prompt, Confirm
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Tutorial: Interaction - Alert, Prompt, Confirm</title>
</head>
<body>
<div class="container">
This is page
</div>
<script>
//Alert in in-browser Javascript Does not return anything
// alert("This is a message")
// Promt in JS
// let name = prompt("What is your name?", "Guest"); // Leave for other browser When need to collect some information
// console.log(name);
// Confirm in JS
let deletePost = confirm("Dou you want to delete this post") ;
// console.log(deletePost)
if(deletePost){
//Code to delete post
console.log("Your post has been deleted successfully");
}
else{
// Code to cancel deletion of the post
console.log("Your post has not been deleted");
}
// console.log(deletePost);
</script>
</body>
</html>
javascript Tutorial: for, while, forEach, Do While Loops
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Loops </title>
</head>
<body>
<div class="container">
This is about loops
</div>
<script>
// console.log("This is tuturioal 55");
// let i = 0;
// for (i=0; i<3; i++){
// console.log(i);
// }
let friends = ["Rohan", "Sanjeev", "Deepti", "SkillF"];
// for (let index = 0; index < friends.length; index++) {
// console.log("Hello friend, " + friends[index]);
// }
// friends.forEach(function f(element){
// console.log("Hello Friend, " + element + "to modern Javascript")
// });
// for (element of friends){
// console.log("Hello Friend, " + element + "to modern Javascript for again")
// };
let employee ={
name:"Harry",
salary:2 ,
channel: "CWH"
}
// Use this loop to iterate over objects in Javascripts
// for (key in employee){
// console.log(`The ${key} of the employee is ${employee[key]}`);
// }
// while loop in JS
// let i = 0;
// while(i<4){
// console.log(`${i} is less than 4`);
// i++;
// }
// do while loop
let j = 34;
do{
console.log(`${j} is less than 4 "we are in do while now"`);
j++;}
while(j<4);
</script>
</body>
</html>
JavaScript Tutorial: Navigating The DOM | 56
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Manipulating DOM</title>
</head>
<body>
<div id="main" class="container">
<ul id = "nav">
<li>Home</li>
<li>About Us</li>
<li>More About Us</li>
<li>Serives</li>
<li>Contact</li>
</ul>
<div class="container">
Another container
</div>
</div>
<script>
let main = document.getElementById('main')
console.log(main);
let nav = document.getElementById('nav')
console.log(nav);
let container = document.getElementsByClassName('container')
console.log(container)
//let sel = document.querySelector('.container')
//console.log("Selector returns", sel)
// let sel = document.querySelector('#nav>li')
// console.log("Selector returns", sel)
let sel = document.querySelectorAll('#nav>li')
console.log("Selector returns", sel)
</script>
</body>
</html>
//Console Chrome page commands
//How to grab elements on Javascripts by ID,
one class can give to multiple elements
one element can give to multiple class
//Get elements by class name,query selector, get elements by ID, major tool
nav.innerHTML
nav.innerHTML = "<li> Dynamic elements</li>"
//To change the li list in Javascript
sel[0].innerHTML = "Love"
'Love'
sel[3].innerHTML = "Goochi"
'Goochi'
JavaScript Tutorial: Events & Listening to Events tut 57
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JS Event</title>
</head>
<style>
#btn{
padding: 10px 14px;
background-color: red;
border: 2px solid black;
color: white;
font-weight: bold;
border-radius: 8px;
cursor: pointer;
}
</style>
<body>
<!-- browser events:
click
contextmenu(right click)
mousehover/mouseout
mousedown/mouseup
mousemove
submit
focus
DOMcontentloaded
transitionend -->
<div class="container">
<h1>This is my heading</h1>
<p id = "para">Lorem ipsum dolor sit amet consectetur adipisicing elit. Reprehenderit temporibus deserunt rem, aliquam fugit animi doloribus tempora sint corrupti fugiat enim expedita commodi quidem provident nulla quisquam maxime quo aperiam dignissimos quibusdam porro, eos ipsum, sunt officiis! Porro hic rem cum? Delectus sequi, ad eligendi voluptate necessitatibus cum assumenda vero molestias doloribus aperiam ipsum nisi, maiores accusantium quos culpa hic placeat aliquam quibusdam, quaerat rem! Hic minima beatae necessitatibus. Alias veritatis accusantium nulla quam doloremque maiores libero velit ut odit provident suscipit error illo minus tempora blanditiis iure quae, ducimus quisquam facilis cumque quia, id aut consequuntur. Autem quaerat vel iure doloremque blanditiis laborum ea amet! Ipsam, mollitia in eligendi magni commodi optio velit earum modi eius magnam nobis minima blanditiis labore facilis omnis necessitatibus nostrum perspiciatis autem voluptatibus possimus illo corrupti dolorem itaque. Consequatur eum officiis cum repellendus vitae. Vel, beatae magni! Cupiditate ut sit esse necessitatibus sint error, qui mollitia quo deleniti repellat similique laborum. Dignissimos asperiores ipsa itaque esse saepe animi suscipit vel fugit pariatur, eaque expedita recusandae aspernatur voluptas. Voluptates autem alias deserunt vero cum harum id animi minima quam non labore sequi dolorum architecto nulla sed aut culpa esse fugiat fuga maxime quibusdam, reiciendis ratione officia iusto! Vitae vel nulla natus adipisci cumque nobis vero rerum inventore accusamus officia velit illum qui, dolorum provident similique saepe? Repellat odit nobis porro tenetur eveniet asperiores recusandae facere soluta vitae? Autem.</p>
<button id ='btn' onclick="toggleHide()">Show/Hide</button>
<script>
let para = document.getElementById('para');
para.addEventListener('mouseover', function run(){
alert('Mouse Inside')
});
para.addEventListener('mouseout', function run(){
alert('Mouse Outside')
});
function toggleHide(){
let btn = document.getElementById('btn');
let para = document.getElementById('para');
if(para.style.display !='none'){
para.style.display = 'none';
}
else
para.style.display = 'block';
}
</script>
</div>
</body>
</html>
JavaScript Tutorial: setInterval & setTimeOut
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Javascirpt SetTimeOut and ClearTimeout</title>
</head>
<body>
<div class="container">
Time now is <span id="time"></span>
</div>
<script>
console.log("This is tutrial 58");
// setTimeout --> Allows us to run the function once after the interval of time
// clearTimeout --> Allows us to run the function repeatedly after the interval of time
//Simple information after some seconds
// function great(){
// console.log("Hello Good Morning" );
// }
// setTimeout(great, 5000);
function great(name, byeText){
console.log("Hello Good Morning" +" " + name + " " + byeText );
}
// timeOut = setTimeout(great, 5000, "Harry", "Take Care");
// console.log(timeOut);
// clearTimeout(timeOut);
// setTimeout(greet(), 12000); --> Wrong as it is calling function inside setTimeout
// intervalId = setInterval(great, 1000, "Harry", "Good Night");
// clearInterval(intervalId);
function displayTime(){
time = new Date();
console.log(time);
document.getElementById('time').innerHTML = time;
}
setInterval(displayTime, 1000);
</script>
</body>
</html>
JavaScript Tutorial: Date & Time In JavaScript- tut59
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Tutorial: Date & Time In JavaScript</title>
</head>
<style>
.container {
font-size: 23px;
background-color: blanchedalmond;
border: 2px solid grey;
padding: 34px;
margin: 4px;
text-align: center;
}
#time {
font-weight: bold;
}
</style>
<body>
<div class="container">
Current time is <span id="time"></span>
</div>
<script>
console.log("This is date and time tutorial");
let now = new Date();
console.log(now);
let dt = new Date(0);
console.log(dt);
// let newDate = new Date("2029-09-30");
// console.log(newDate);
// let newDate = new Date(year, month, date, hours, minutes, seconds, milliseconds);
let newDate = new Date(3020, 4, 6, 9, 3, 2, 34);
console.log(newDate);
let yr = newDate.getFullYear();
console.log("The year is ", yr);
let dat = newDate.getDate();
console.log("The year is ", dat);
let month = newDate.getMonth();
console.log("The year is ", month);
let hours = newDate.getHours();
console.log("The year is ", hours);
let minutes = newDate.getMinutes();
console.log("The year is ", minutes);
let seconds = newDate.getSeconds();
console.log("The year is ", seconds);
let milliseconds = newDate.getMilliseconds();
console.log("The year is ", milliseconds);
newDate.setDate(8);
newDate.setMinutes(29);
console.log(newDate);
setInterval(updateTime, 1000);
function updateTime() {
time.innerHTML = new Date();
}
</script>
</body>
</html>
JavaScript Tutorial: Arrow Functions In JavaScript --Tut60
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Arrow Function</title>
</head>
<body>
<div class="container">
This is arrow Function tutorials
</div>
<script>
//Arrow function
// let greet = ()=> {
// console.log('Good morning');
// }
//Using short form of above code
let greet = () => console.log('Good morning');
// let sum = (a, b)=>{
// return a+b;
// }
let sum2 = (a, b) => a + b;
let half = a => a / 2;
// function greet ();{
// console.log("Good morning");
// }
greet();
setTimeout(() => {
console.log("We are indside");
}, 3000);
let obj1 = {
greeting: "Good morning",
names: ["Prateek", "Rohit", "Rana", "Ravi", "Prabha"],
speak() {
this.names.forEach((student) => {
console.log(this.greeting + "Kukdo koo" + student);
});
}
}
obj1.speak();
//Laxical This:
// Kisi bhi object ke andar ek function banaya uske andar arrow function use karte ho to jo this hota hain wo parent ka this hota hain.
// Lekin arrow function use nahi kiya hain to us function ka apna this hota hain.
</script>
</body>
</html>
JavaScript Tutorial: Math Object In JavaScript tut61
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Math Object</title>
</head>
<body>
<div class="container">
<h1>This is math tutorial</h1>
</div>
<script>
let m = Math;
console.log(m)
//Printing the constants form Math object
console.log("The value of Math.E is ", Math.E)
console.log("The value of Math.PI is ", Math.PI)
console.log("The value of Math.LN2 is ", Math.LN2)
console.log("The value of Math.SQRT1_2 is ", Math.SQRT1_2)
console.log("The value of Math.LOG2E is ", Math.LOG2E)
console.log("The value of Math.LN10 is ", Math.LN10)
//Printing the function form Math object
let a = 34.64534;
let b = 89;
console.log("The value of a and b is ", a, b);
console.log("The value of a and b is ", Math.round(a), Math.round(b));
console.log("3 rasied to the power of 2 is ", Math.pow(3,2))
console.log("2 rasied to the power of 12 is ", Math.pow(2,12))
console.log("1 rasied to the power of 2 is ", Math.pow(1,2))
console.log("1 rasied to the power of 2 is ", Math.pow(1,2))
console.log("Square root of 36 is ", Math.sqrt(36))
console.log("Square root of 64 is ", Math.sqrt(64))
console.log("Square root of 50 is ", Math.sqrt(50))
console.log("Square root of 2 is ", Math.sqrt(2))
//Ceil and floor
console.log("5.8 rounded up nearest intger", Math.ceil(5.8))
console.log("5.8 rounded updown nearest intger", Math.floor(5.8))
//Absolute value
console.log("Absolue value is 5.66", Math.abs(5.66))
console.log("Absolue value is -5.66", Math.abs(-5.66))
//Trignometric function
console.log("The value of sin(pi) is ", Math.sin(Math.PI/2))
console.log("The value of tan(pi) is ", Math.tan(Math.PI/2))
console.log("The value of cos(pi) is ", Math.cos(Math.PI/2))
//Min & Max function
console.log("Minimum value of 4,5,6 is", Math.min(4,5,6))
console.log("Maximum value of 14,5,6 is", Math.max(14,5,6))
//Generating random number
let r = Math.random();
//Random number between a and b number (a,b) = a + (b-a)*Math.random()
let a1 = 50;
let b1 = 60;
let r1_100 = a1 + (b1-a1)*Math.random();
console.log("The random is between 1 to 100 ",r1_100)
console.log("The random is between 1 to 0 ",r)
</script>
</body>
</html>
JavaScript Tutorial: Working with JSON in JavaScript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JSON Tutorial</title>
</head>
<body>
<div class="container">
This is my container
</div>
<script>
let jsonObj = {
name: "Harry",
channel: "CWH",
friend: "Rohan Das",
food: "Bhindi",
}
console.log(jsonObj)
//JSON to string
let myJsonStr = JSON.stringify(jsonObj);
console.log(myJsonStr)
//Replace string item
myJsonStr = myJsonStr.replace('Harry', 'Larry');
console.log(myJsonStr)
//String to JSON back
newJsonObj = JSON.parse(myJsonStr);
console.log(newJsonObj)
</script>
</body>
</html>
Node.Js Introduction and Installation --t
//console.log("Hello World");
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');
res.end(`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Test</title>
</head>
<body>
<h1>iAffordable Solution</h1>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quidem in totam debitis reiciendis nihil delectus rem velit beatae, maiores recusandae error ab. Distinctio culpa architecto, nobis maiores aspernatur dignissimos blanditiis iure accusamus corrupti similique.</p>
</body>
</html>`);
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`); Node.Js Modules with Examples tut64
// If only want to access a file data
// const fs = require("fs");
// const text = fs.readFileSync("test.text", "utf-8");
// console.log("The content of the file is ");
// console.log(text);
//If want to replace the data
const fs = require("fs")
let text = fs.readFileSync("test.text", "utf-8");
text = text.replace("read", "Rohan")
console.log("The content of the file is ")
console.log(text);
console.log("Creating a new file....");
fs.writeFileSync("rohan.txt", text);
Blocking vs Non-Blocking execution tut-65
// Synchornous or blocking
//-line by line execution
//Asynchornouse or non-blocking
//- line by line execution not graunteed -
//- callback will fire
const fs = require("fs");
fs.readFile("test.text", "utf-8", (err, data)=>{
console.log(data);
});
console.log("This is a message")
Serving HTML Files using NodeJs -tut66
const http = require('http')
const fs = require('fs')
const fileContent = fs.readFileSync('tut61.html')
const server = http.createServer((req, res)=>{
res.writeHead(200, {'Content-type':'text/html'});
res.end(fileContent)
})
server.listen(80, '127.0.0.1', ()=>{
console.log("Listing on port 80")
} )
Creating a Custom Backend Using NodeJs tut 67 foler
const http = require('http');
const fs = require('fs');
const hostname = '127.0.0.1';
const port = 3000;
const home = fs.readFileSync('index.html')
const about = fs.readFileSync('./about.html')
const services= fs.readFileSync('./services.html')
const contact = fs.readFileSync('./contact.html')
const server = http.createServer((req, res)=>{
console.log(req.url)
url = req.url;
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');
if (url == '/'){
res.end(home);
}
else if (url == '/about'){
res.end(about);
}
else if (url == '/services'){
res.end(services);
}
else if (url == '/contact'){
res.end(contact);
}
else {
res.statusCode = 404;
res.end('<h1> 404 not found </h1>');
}
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
index, and other pages https://github.com/Spartan456/Node-JS-1-project/settings
Creating Custom Modules in Node Using NodeJ Tut 68
function average(arr){
let sum = 0;
arr.forEach(element => {
sum += element;
});
return sum/arr.length;
}
// module.exports = average;
// module.exports = {
// avg: average,
// name: "Deepak",
// repo: "Github"
// }
module.exports.name= "Ravi"
// const average = require("./mod");
// console.log(average([3,4]))
const mod = require("./mod");
console.log(mod.name)
// console.log(mod.avg([3,8]))
console.log("This is index.js" );


Comments
Post a Comment