27 | Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc
28 | malesuada justo in risus bibendum aliquet.
29 |
30 |
31 |
32 |
33 |
Section 2
34 |
35 | Vivamus ac lacinia quam, vitae eleifend velit. Integer sit amet libero
36 | sit amet risus tristique mollis sed quis ipsum.
37 |
38 |
39 |
40 |
41 |
Section 3
42 |
43 | Donec feugiat dolor id sapien interdum, a ullamcorper nisl malesuada.
44 | Etiam nec feugiat leo.
45 |
46 |
47 |
48 |
49 |
52 |
53 |
54 |
--------------------------------------------------------------------------------
/06. Modules/README.md:
--------------------------------------------------------------------------------
1 | ## ⭐ Core Modules
2 | Core modules are built into Node.js and come with its installation. They provide basic functionalities like creating an HTTP server (`http`), handling the file system (`fs`), dealing with file paths (`path`), providing OS info (`os`), and handling binary data (`buffer`). You can load these modules using the `require` function. 📚
3 |
4 | ## ⭐ Global Modules
5 | Global modules are Node.js packages installed system-wide, meaning they can be used anywhere on your computer without importing them into your project. For instance, if you install `nodemon` globally, you can use it anywhere on your computer by simply running `nodemon` in your terminal. 🌐
6 |
7 | ```js
8 | console.log("Hello World") // console.log is a global module
9 | ```
10 |
11 | ## ⭐ Non-global Modules
12 | Non-global modules in Node.js are not part of the Node.js core and are not installed globally. They are created locally within your Node.js application and need to be imported into your project before use. 📁
13 |
14 | - Example 1:
15 | ```js
16 | const fs = require('fs')
17 | fs.writeFileSync('hello.txt', 'Hello World') // fs (file system) is a non-global module
18 | ```
19 |
20 | - Example 2:
21 | ```js
22 | console.log("Our directory is " + __dirname) // __dirname is a non-global module
23 | console.log("Our file name is " + __filename) // __filename is a non-global module
24 | ```
25 |
26 | ⚡ It's recommended to always place `const abc = require('abc')` at the top of the file.
27 |
28 | > If you want to import only a specific function from a module, you can use the destructuring syntax:
29 |
30 | ```js
31 | const { writeFileSync } = require('fs')
32 | writeFileSync('hello.txt', 'Hello World')
33 | ```
34 | or
35 | ```js
36 | const fs = require('fs').writeFileSync;
37 | fs('hello.txt', 'Hello World')
38 | ```
39 | You can even change the variable name of the function:
40 | ```js
41 | const abc = require('fs').writeFileSync;
42 | abc('hello.txt', 'Hello World')
43 | ```
--------------------------------------------------------------------------------
/07. Create Basic Server/README.md:
--------------------------------------------------------------------------------
1 |
🚀 Basic Server Creation:
2 |
3 | - Create a file named `server.js` in the project root.
4 |
5 | - Add the following code to set up the server:
6 |
7 | ```js
8 | const http = require('http');
9 | ```
10 | > Handles server requests and responses.
11 |
12 | - Create the server using `createServer()` and listen on port 4500:
13 |
14 | ```js
15 | http.createServer((req, res) => {
16 | res.write('Hello World');
17 | res.end();
18 | }).listen(4500);
19 | ```
20 | > - `createServer()` creates the server.
21 | > - `listen(4500)` sets the server to run on port 4500.
22 |
23 | - Run the server with:
24 |
25 | ```bash
26 | node server.js
27 | ```
28 |
29 | - Open `localhost:4500` in the browser to see the output:
30 |
31 | ```bash
32 | Hello World
33 | ```
34 |
35 | - Additional: Send HTML to the client:
36 |
37 | ```js
38 | http.createServer((req, res) => {
39 | res.write('
45 |
46 | 1. Create a function named `data()` and pass `req` and `res`:
47 |
48 | ```js
49 | const data = (req, res) => {
50 | res.write('Hello World');
51 | res.end();
52 | }
53 | ```
54 | or
55 | ```js
56 | function data(req, res) {
57 | res.write('Hello World');
58 | res.end();
59 | }
60 | ```
61 |
62 | 2. Pass the `data` function to `createServer()`:
63 |
64 | ```js
65 | http.createServer(data).listen(4500);
66 | ```
67 |
68 |
🧐 Understanding Arrow Functions:
69 |
70 | - Arrow functions provide a concise syntax:
71 |
72 | ```js
73 | // Normal Function
74 | function multiply(a, b) {
75 | return a * b;
76 | }
77 |
78 | // Arrow Function
79 | const multiply = (a, b) => a * b;
80 | ```
81 |
82 | > No need for the `return` statement in arrow functions if it's a single line.
83 |
84 |
9 |
10 | 1. If NodeJS is installed, you can check the version by running the following command in your terminal:
11 | ```bash
12 | node -v
13 | ```
14 | 2. Type `node` in your terminal to start the NodeJS REPL (Read-Eval-Print-Loop) environment.
15 |
16 | 3. Type `console.log("Hello World")` in the REPL and press enter to print "Hello World" in the terminal.
17 | 4. Let's do some operation check it out.
18 | ```bash
19 | var a = 10; //enter
20 | console.log(a); //output: 10
21 | ```
22 | 4. You can notice `undefined` in the output.
23 | > This is because the expression does not return any value. It just assigns the value to the variable when you do `console.log(a)`, it prints the value of the variable `a` which is `10`.
24 |
25 | 5. You can also do some mathematical operation in the REPL.
26 | ```bash
27 | var a = 10; //enter
28 | var b = 20; //enter
29 | console.log(a+b); //output: 30
30 | ```
31 | 6. Create a folder named `nodeJs` and open cmd in that folder and type `code .` to open the folder in VS Code.
32 | 7. Make a file named `index.js` and type the following code in it.
33 | > NodeJs is not a language, it is a runtime environment. It is used to run JavaScript code outside the browser. It is built on top of the V8 JavaScript engine. It is used to build server-side applications.
34 | ```js
35 | console.log("Hello World");
36 | ```
37 | 8. Now open the terminal in VS Code and type `node index.js` to run the code.
38 |
39 |
40 |
41 | > In vs code terminal if you compile by `node index.js` then you will the output of console.log() in the terminal and in browser you will get the output of `console.log()` in the browser console. Now the question is here the `console.log` is same in two place ?
42 |
43 | - Node.js has a built-in console module that provides a simple debugging console similar to the JavaScript console mechanism provided by web browsers. The console module exports two specific components: a Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream; and a global console instance configured to write to process.stdout and process.stderr.
44 |
45 | The implementation of the console object is similar in both Node.js and web browsers, which is why you can use methods like console.log() in the same way in both environments.
46 |
47 |
--------------------------------------------------------------------------------
/Typescript_Experiment_Same_Chapters/server/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "fullstack_advance",
3 | "version": "1.0.0",
4 | "main": "index.js",
5 | "repository": "https://github.com/Subham-Maity/fullstack_advance.git",
6 | "author": "Subham <97989643+Subham-Maity@users.noreply.github.com>",
7 | "license": "MIT",
8 | "scripts": {
9 | "start": "nodemon src/server.ts",
10 | "dev": "rimraf dist && concurrently \"npm run build:watch\" \"npm run start\"",
11 | "start:dev": "nodemon src/server.ts",
12 | "build": "rimraf dist && npx tsc",
13 | "build:watch": "npx tsc -w",
14 | "preserve": "npm run build",
15 | "prod": "concurrently \"npm run build\" \"npm run start\"",
16 | "compile": "npx tsc",
17 | "deploy": "nodemon src/server.ts",
18 | "day6": "nodemon --exec ts-node day6.ts",
19 | "day7": "nodemon --exec ts-node day7.ts",
20 | "day11" : "nodemon --exec ts-node day11.ts"
21 | },
22 | "keywords": [],
23 | "dependencies": {
24 | "@aws-sdk/client-s3": "^3.485.0",
25 | "@aws-sdk/s3-request-presigner": "^3.485.0",
26 | "aws-sdk": "^2.1531.0",
27 | "axios": "^1.6.7",
28 | "bcrypt": "^5.1.1",
29 | "compression": "^1.7.4",
30 | "concurrently": "^7.4.0",
31 | "config": "^3.3.9",
32 | "cookie-parser": "^1.4.6",
33 | "cors": "^2.8.5",
34 | "dayjs": "^1.11.10",
35 | "dotenv": "^16.3.1",
36 | "express": "^4.18.2",
37 | "googleapis": "^129.0.0",
38 | "helmet": "^7.1.0",
39 | "ioredis": "^5.3.2",
40 | "jsonwebtoken": "^9.0.2",
41 | "lodash": "^4.17.21",
42 | "mailgen": "^2.0.28",
43 | "moment-timezone": "^0.5.43",
44 | "mongoose": "^8.0.3",
45 | "morgan": "^1.10.0",
46 | "multer": "^1.4.5-lts.1",
47 | "nodemailer": "^6.9.8",
48 | "nodemon": "^3.0.2",
49 | "openapi-types": "^7.2.3",
50 | "otp-generator": "^4.0.1",
51 | "pino": "^8.17.1",
52 | "pino-pretty": "^10.3.0",
53 | "prettier": "^3.1.1",
54 | "rimraf": "^3.0.2",
55 | "sharp": "^0.33.1",
56 | "swagger-jsdoc": "^6.2.8",
57 | "swagger-ui-express": "^5.0.0",
58 | "typescript": "^5.3.3",
59 | "uuid": "^9.0.1",
60 | "zod": "^3.22.4"
61 | },
62 | "devDependencies": {
63 | "@types/bcrypt": "^5.0.2",
64 | "@types/body-parser": "^1.19.5",
65 | "@types/compression": "^1.7.5",
66 | "@types/config": "^3.3.3",
67 | "@types/cookie-parser": "^1.4.6",
68 | "@types/cors": "^2.8.17",
69 | "@types/express": "^4.17.21",
70 | "@types/jsonwebtoken": "^9.0.5",
71 | "@types/lodash": "^4.14.202",
72 | "@types/morgan": "^1.9.6",
73 | "@types/multer": "^1.4.11",
74 | "@types/node": "^20.11.8",
75 | "@types/nodemailer": "^6.4.14",
76 | "@types/otp-generator": "^4.0.2",
77 | "@types/swagger-jsdoc": "^6.0.4",
78 | "@types/swagger-ui-express": "^4.1.6",
79 | "@types/uuid": "^9.0.7",
80 | "ts-node": "^10.9.2"
81 | }
82 | }
83 |
--------------------------------------------------------------------------------
/10. Nodemon Package/README.md:
--------------------------------------------------------------------------------
1 |
2 | ## ⭐ What is Nodemon Package
3 |
4 |
5 |
6 |
9 |
10 |
11 |
12 |
13 | Suppose you made a change in your code and you want to see the changes in your browser. You have to stop the server and start it again. This is a very time-consuming process. So, to avoid this, we use the nodemon package. Nodemon is a package that automatically restarts the node application when file changes in the directory are detected.
14 |
15 |
16 |
17 |
18 | ## ⭐ How to Install Nodemon Package
19 |
20 |
21 |
22 | 1. First, search for the nodemon package in the npm website. Then, click on the link to go to the npm [website](https://www.npmjs.com/package/nodemon).
23 | - Copy the installation command from the npm website `npm i nodemon`
24 |
25 | - If you add `-g` at the end of the command, it will install the package globally. So you can use it in any project. `npm i nodemon -g`
26 |
27 | > If you are using mac or linux you have to add `sudo` before the command. `sudo npm i nodemon -g`
28 |
29 | 2. Now, open your terminal and go to the project directory. Then, paste the command in the terminal and press enter.
30 |
31 | 3. Now, you can see the nodemon package in the package.json file.
32 |
33 | 4. Now you can use the nodemon package in your project. You can use the nodemon package in two ways.
34 |
35 | - You can use the nodemon package in the package.json file. You can add the nodemon package in the `scripts` section of the package.json file. Then, you can use the nodemon package by running the command `npm run dev`.
36 |
37 | ```json
38 | {
39 | "scripts": {
40 | "start": "node app.js",
41 | "dev": "nodemon app.js"
42 | },
43 | }
44 | ```
45 |
46 |
47 | - You can use the nodemon package in the terminal. You can use the nodemon package by running the command `nodemon app.js` or `nodemon app.js -e js,html,css` (if you want to use nodemon for multiple file types).
48 |
49 | 5. Now if you make any changes in your code, nodemon will automatically restart the server.
50 |
51 |
52 |
53 |
54 |
55 |
56 | - Node.js is an asynchronous language.
57 |
58 | Suppose in other language if one function is running and you call another function, the second function will wait for the first function to finish. But in Node.js, if one function is running and you call another function, the second function will not wait for the first function to finish this is called asynchronous.
59 |
60 |
61 |
62 | > It uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. This means that Node.js can handle multiple requests simultaneously without waiting for one request to complete before moving on to the next.
63 |
64 |
--------------------------------------------------------------------------------
/05. Fundamentals and Features/README.md:
--------------------------------------------------------------------------------
1 | ## ⭐ Fundamentals and Features
2 |
3 |
4 |
5 |
6 |
7 |
10 |
11 |
12 | For NodeJs you need to have a basic knowledge of Javascript. If you are new to Javascript then you can check out my [tutorial on Javascript](https://codexam.vercel.app/docs/js)
13 |
14 | ### Some Important Notes
15 |
16 | 1. Suppose you make a file `app.js` and another file `index.js` and you want to import the `app.js` file like this
17 |
18 | ```js filename="app.js"
19 | export const name = "Subham Maity"
20 | export const age = 20
21 | ```
22 |
23 | ```js filename="index.js"
24 | import {name,age} from "./app.js"
25 | ```
26 | And in your terminal you run `node index.js` then you will get an error like this
27 | ```bash
28 | SyntaxError: Cannot use import statement outside a module
29 | ```
30 | This is because NodeJs doesn't support the `import` and `export` syntax. So you have to use the `module.exports` and `require` syntax.
31 |
32 | ```js filename="app.js"
33 | module.exports = {
34 | name: "Subham Maity",
35 | age: 20
36 | }
37 | ```
38 |
39 | ```js filename="index.js"
40 | const {name,age} = require("./app.js")
41 |
42 | console.log(name,age)
43 | ```
44 |
45 | Now if you run `node index.js` then you will get the output like this
46 | ```bash
47 | Subham Maity 20
48 | ```
49 | 2. You can even create a function in `app.js` and export it and then import it in `index.js` and use it.
50 |
51 | ```js filename="app.js"
52 | module.exports = {
53 | add: (a,b) => a+b
54 | }
55 | ```
56 |
57 | ```js filename="index.js"
58 | const app = require("./app.js")
59 |
60 | console.log(app.add(2,3))
61 | ```
62 |
63 | Now if you run `node index.js` then you will get the output like this
64 |
65 | ```bash
66 | 5
67 | ```
68 |
69 |
70 | What is filter in Javascript ?
71 |
72 | - If you have a array like this
73 |
74 | ```js
75 | const arr = [1,2,3,4,5,6,7,8,9,10]
76 | ```
77 | and you want to traverse through the array and get the elements which are greater than 5 then you can use the `filter` method.
78 |
79 | ```js
80 | const arr = [1,2,3,4,5,6,7,8,9,10]
81 |
82 | const greaterThan5 = arr.filter((element) => element > 5)
83 |
84 | console.log(greaterThan5)
85 |
86 | ```
87 |
88 | Now if you run `node index.js` then you will get the output like this
89 |
90 | ```bash
91 | [ 6, 7, 8, 9, 10 ]
92 | ```
93 |
94 | - If you have a array like this
95 |
96 | ```js
97 | const arr1 = [1,2,3,4,4,4,5,6,7,8,9,10]
98 | ```
99 | and you want to traverse and find the value that is repeated the most then you can use the `filter` method.
100 |
101 | ```js
102 | const arr1 = [1,2,3,4,4,4,5,6,7,8,9,10]
103 |
104 | const mostRepeated = arr1.filter((element) =>
105 | {
106 | return element === 4
107 | })
108 |
109 | console.log(mostRepeated)
110 |
111 | ```
112 |
113 | Even you can you gretter than 5 and less than 8
114 |
115 | ```js
116 | const arr1 = [1,2,3,4,4,4,5,6,7,8,9,10]
117 |
118 | const mostRepeated = arr1.filter((element) =>
119 | {
120 | return element > 5 && element < 8
121 | })
122 |
123 | console.log(mostRepeated)
124 |
125 | ```
126 |
127 |
128 |
129 |
--------------------------------------------------------------------------------
/Experiments/nodeJs11/data.js:
--------------------------------------------------------------------------------
1 | const data = [
2 | {
3 | name: "Rajesh",
4 | age: 20,
5 | address: {
6 | city: "Delhi",
7 | state: "Delhi",
8 | country: "India",
9 | },
10 | hobbies: ["coding", "reading", "playing"],
11 | skills: ["html", "css", "js", "nodejs"],
12 | education: {
13 | school: "Delhi Public School",
14 | college: "Delhi University",
15 | degree: "B.Tech",
16 | },
17 | projects: {
18 | project1: "Portfolio",
19 | project2: "Blog",
20 | project3: "E-commerce",
21 | },
22 | social: {
23 | github: "rajesh.github.io",
24 | linkedin: "rajesh.linkedin.com",
25 | twitter: "rajesh.twitter.com",
26 | },
27 | work: {
28 | company: "XYZ",
29 | position: "Software Engineer",
30 | experience: "2 years",
31 | },
32 | achievements: {
33 | achievement1: "Won a hackathon",
34 | achievement2: "Got a scholarship",
35 | achievement3: "Got a job",
36 | },
37 | interests: {
38 | interest1: "Reading",
39 | interest2: "Playing",
40 | interest3: "Coding",
41 | },
42 | languages: {
43 | language1: "English",
44 | language2: "Hindi",
45 | language3: "Punjabi",
46 | },
47 | contact: {
48 | phone: "1234567890",
49 | email: "rajesh.dev.com",
50 | },
51 | },
52 | {
53 | name: "Subham",
54 | age: 20,
55 | address: {
56 | city: "Delhi",
57 | state: "Delhi",
58 | country: "India",
59 | },
60 | hobbies: ["coding", "reading", "playing"],
61 | skills: ["html", "css", "js", "nodejs"],
62 | education: {
63 | school: "Delhi Public School",
64 | college: "Delhi University",
65 | degree: "B.Tech",
66 | },
67 | projects: {
68 | project1: "Portfolio",
69 | project2: "Blog",
70 | project3: "E-commerce",
71 | },
72 | social: {
73 | github: "subham.github.io",
74 | linkedin: "subham.linkedin.com",
75 | twitter: "subham.twitter.com",
76 | },
77 | work: {
78 | company: "XYZ",
79 | position: "Software Engineer",
80 | experience: "2 years",
81 | },
82 | achievements: {
83 | achievement1: "Won a hackathon",
84 | achievement2: "Got a scholarship",
85 | achievement3: "Got a job",
86 | },
87 | interests: {
88 | interest1: "Reading",
89 | interest2: "Playing",
90 | interest3: "Coding",
91 | },
92 | languages: {
93 | language1: "English",
94 | language2: "Hindi",
95 | language3: "Punjabi",
96 | },
97 | contact: {
98 | phone: "1234567890",
99 | email: "subham.dev.com",
100 | },
101 | },
102 | {
103 | name: "Rahul",
104 | age: 20,
105 | address: {
106 | city: "Delhi",
107 | state: "Delhi",
108 | country: "India",
109 | },
110 | hobbies: ["coding", "reading", "playing"],
111 | skills: ["html", "css", "js", "nodejs"],
112 | education: {
113 | school: "Delhi Public School",
114 | college: "Delhi University",
115 | degree: "B.Tech",
116 | },
117 | projects: {
118 | project1: "Portfolio",
119 | project2: "Blog",
120 | project3: "E-commerce",
121 | },
122 | social: {
123 | github: "rahul.github.io",
124 | linkedin: "rahul.linkedin.com",
125 | twitter: "rahul.twitter.com",
126 | },
127 | work: {
128 | company: "XYZ",
129 | position: "Software Engineer",
130 | experience: "2 years",
131 | },
132 | achievements: {
133 | achievement1: "Won a hackathon",
134 | achievement2: "Got a scholarship",
135 | achievement3: "Got a job",
136 | },
137 | interests: {
138 | interest1: "Reading",
139 | interest2: "Playing",
140 | interest3: "Coding",
141 | },
142 | languages: {
143 | language1: "English",
144 | language2: "Hindi",
145 | language3: "Punjabi",
146 | },
147 | contact: {
148 | phone: "1234567890",
149 | email: "rahul.dev.com",
150 | },
151 | },
152 | ];
153 |
154 | module.exports = data;
155 |
--------------------------------------------------------------------------------
/16. Handle Asynchronous Data/README.md:
--------------------------------------------------------------------------------
1 | ## ⭐ How to handle asynchronous data in Node js
2 |
3 |
4 |
5 |
8 |
9 |
10 |
11 |
12 |
13 |
14 | Problem Statement :
15 |
16 | ```js filename="index.js"
17 |
18 | let x=10;
19 | let y=0;
20 |
21 | setTimeout(() => {
22 | y = 20;
23 | }, 2000);
24 |
25 | console.log(x+y);
26 | ```
27 |
28 | ```js filename="result.js"
29 |
30 | 10
31 |
32 | ```
33 | You can see even I set y=20 after 2 seconds, the result is 10. Why is that? Because the setTimeout function is asynchronous. It means it will not wait for the function to complete. It will execute the next line of code. So, the result is 10.
34 |
35 | But what if I want to wait for the function to complete and then execute the next line of code so that the result will be 30. How can I do that?
36 |
37 |
38 | ### Solution
39 |
40 | We will use the promise to solve this problem.
41 |
42 |
43 |
44 | A promise is like a commitment to do something. When you make a promise, it's like saying "I will do this thing". At first, the promise is just waiting for you to do the thing you promised.
45 |
46 | Once you actually do the thing, the promise is either kept or broken. If you successfully do the thing you promised, the promise is kept and you can say that it was "resolved". But if something goes wrong and you can't do the thing you promised, the promise is broken and you can say that it was "rejected".
47 |
48 | So, a promise starts off as pending, waiting for you to do the thing you promised. Once you actually do it, the promise is either resolved or rejected, depending on whether you were able to do it successfully.
49 |
50 |
51 | The Promise object has two states:
52 |
53 | - Pending: The Promise is in a state of flux, and the result of the asynchronous operation has not yet been determined.
54 | - Fulfilled: The Promise has been fulfilled, and the result of the asynchronous operation is available.
55 | - Rejected: The Promise has been rejected, and the asynchronous operation failed.
56 |
57 | > - To solve this, we use a Promise. A Promise is like a container that holds a value that might not be available yet but will be in the future.
58 | > - Promises are used to handle asynchronous data in Node js and it takes two arguments, resolve and reject
59 | > - The resolve function is called when the Promise is successful and the reject function is called when the Promise is unsuccessful.
60 | > - They are used to avoid callback hell and make code more readable and maintainable.
61 | > - You can use the then method to attach handlers to a promise that will be called when the promise is settled
62 |
63 |
64 |
65 | - 1. We create a Promise called `waitingData` and use `setTimeout` inside it.
66 | - 2. After 2 seconds, we give the Promise the new value (20) using `resolve(20)`.
67 | - 3. We then use the `then()` method to handle the Promise's value when it's ready.
68 | - 4. Inside the `then()` method, we update `y` with the new value and log the sum of `x` and `y`.
69 | > the `then()` method is called when the promise is settled and it takes two arguments, resolve and reject and it is used to attach handlers to a promise that will be called when the promise is settled
70 | - 5. By using a Promise, we make sure to log the sum only after the value of `y` is updated.
71 |
72 | ```js filename="index.js"
73 |
74 | let x = 10;
75 | let y = 0;
76 |
77 | // Create a new Promise called waitingData
78 | let waitingData = new Promise((resolve, reject) => {
79 | // Set a timeout of 2 seconds
80 | setTimeout(() => {
81 | // Resolve the Promise with the value 20
82 | resolve(20);
83 | }, 2000);
84 | });
85 |
86 | // Use .then() to handle the resolved value of the Promise
87 | waitingData.then((data) => {
88 | // Set the value of b to be equal to the resolved value (which is 20)
89 | let b = data;
90 | // Log the result of adding x and b together to the console
91 | console.log(x + b);
92 | });
93 | ```
94 | ```js filename="result.js"
95 |
96 | 30
97 | ```
98 |
99 | > A Promise is an object that represents the eventual completion or failure of an asynchronous operation.
100 |
101 |
102 |
--------------------------------------------------------------------------------
/15. Synchronous & Asynchronous/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | ## ⭐ What is Synchronous ?
5 |
6 |
7 |
8 |
11 |
12 |
13 |
14 |
15 | Synchronous: Tasks run one after another, waiting for each to finish before starting the next. Example: Washing clothes, then drying, then ironing. Each task waits for the previous to finish.
16 |
17 |
18 | Suppose I have three functions. `Function A` , `Function B` , `Function C`.
19 |
20 | In this case,
21 | - `Function A` runs and completes
22 | - `Function B` runs after `Function A` completes and completes
23 | - `Function C` runs after `Function B` completes and completes
24 |
25 |
26 | > The next function doesn't start until the previous one has completed. In other words, the functions are executed in a sequential order.
27 |
28 |
29 |
30 |
31 | ## ⭐ What is Asynchronous ?
32 |
33 |
34 | Asynchronous: Tasks can run simultaneously, not waiting for others to finish. Example: Washing clothes, while another set is drying, and another is being ironed. Tasks happen independently without waiting.
35 |
36 |
37 | Suppose I have three functions. `Function A` , `Function B` , `Function C`.
38 |
39 | In this case,
40 | - `Function A` runs and starts in the background
41 | - `Function B` runs and starts in the background
42 | - `Function C` runs and starts in the background
43 | - `Function A` completes
44 | - `Function B` completes
45 | - `Function C` completes
46 |
47 |
48 | > The next function doesn't have to wait for the previous one to complete before starting. In other words, the functions are executed concurrently.
49 |
50 |
51 |
52 |
53 |
54 | ## ⭐ Synchronous Basic Code
55 |
56 |
57 |
58 | ```js filename="index.js"
59 |
60 | console.log("Function 1");
61 | console.log("Function 2");
62 | console.log("Function 3");
63 | ```
64 |
65 | ```bash filename="output"
66 |
67 | Function 1
68 | Function 2
69 | Function 3
70 | ```
71 |
72 |
73 | In this example, the program will execute the functions one after the other in order. So it will log "Function 1", then "Function 2", and then "Function 3".
74 |
75 | This is because synchronous execution means that the program will wait for a function to finish before moving on to the next one.
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 | ## ⭐ Asynchronous Basic Code
84 |
85 |
86 | ```js filename="index.js"
87 |
88 | console.log("Function 1");
89 | setTimeout(() => {
90 | console.log("Function 2");
91 | }, 2000);
92 | console.log("Function 3");
93 | ```
94 |
95 | ```bash filename="output"
96 |
97 | Function 1
98 | Function 3
99 | Function 2
100 | ```
101 |
102 |
103 | In this example,
104 |
105 | - The code starts by logging "Function 1" to the console.
106 | - The setTimeout function is called, which delays the execution of its callback function by 2000 milliseconds (2 seconds).
107 | - While the setTimeout function is waiting for the delay to complete, the program moves on to the next line of code, which logs "Function 3" to the console.
108 | - After 2 seconds, the callback function inside the setTimeout function is executed, logging "Function 2" to the console.
109 |
110 | So even though the setTimeout function is called before "Function 3" is logged, it doesn't block the program from executing the next line of code, resulting in "Function 3" being logged before "Function 2".
111 |
112 |
113 |
114 |
115 | ## ⭐ Asynchronous More Examples
116 |
117 |
118 | ```js filename="index.js"
119 |
120 | let x=10;
121 | let y=0;
122 |
123 | setTimeout(() => {
124 | y = 20;
125 | }, 2000);
126 |
127 | console.log(x+y);
128 | ```
129 |
130 | ```bash filename="output"
131 | 10
132 | ```
133 |
134 | Instead of 30 we get 10. This is because the setTimeout function is called after the console.log function, so the program will log 10(x+y where y=0) to the console before the setTimeout function is executed, which sets y to 20.
135 |
136 | > setTimeout is a function that is built into the browser. It takes two arguments: a callback function and a delay in milliseconds. The callback function is executed after the delay has passed.
137 |
138 |
139 | > In Synchronous operations tasks are performed one at a time,
140 | > In Asynchronous, Second Task do not wait to finish First Task
141 |
142 |
143 |
144 |
--------------------------------------------------------------------------------
/02. Basic Concepts and Theory of Node js/README.md:
--------------------------------------------------------------------------------
1 | # [Website View](https://codexam.vercel.app/docs/node/node2)
2 |
3 | ## ⭐ What are Client and Server Sides?
4 |
5 |
6 |
7 |
8 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 | **Client-side** code runs on the user's web browser, while **server-side** code runs on the web server. For example:
20 |
21 | - **Client-side code** can use **HTML**, **CSS**, and **JavaScript** to create the web page layout, style, and interactivity. It can also fetch data from the server using AJAX.
22 | - **Server-side code** can use **Node.js** or other languages to handle requests from the client, access the database, and send back data. It can also run business logic and authentication.
23 |
24 | A real-world example is [Gmail](https://mail.google.com/). The client-side code loads the web page and sends requests to the server-side code to fetch your emails. The server-side code validates your identity and sends back the data to the client-side code.
25 |
26 |
27 | ## ⭐ How NodeJs use JavaScript?
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 | Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine, which allows JavaScript to be executed outside of a browser environment.
37 |
38 | **V8 JavaScript Engine:** Node.js uses the V8 engine to compile and execute JavaScript code. This engine was originally developed by Google for their Chrome browser, and it provides high-performance execution of JavaScript code outside of the browser. [Ryan Dahl](https://en.wikipedia.org/wiki/Ryan_Dahl) (the creator of Node.js) used the V8 engine to create Node.js. Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine, which allows JavaScript to be executed outside of a browser environment.
39 |
40 | Here's an example of how Node.js uses JavaScript:
41 | > If you can't understand the code, don't worry. We'll explain it later.
42 |
43 | ```js
44 | // This is a simple Node.js HTTP server that responds to requests with "Hello, World!"
45 | const http = require('http'); // Import the Node.js HTTP module
46 |
47 | const server = http.createServer((req, res) => {
48 | res.writeHead(200, {'Content-Type': 'text/plain'}); // Set the response headers
49 | res.write('Hello, World!'); // Write the response body
50 | res.end(); // End the response
51 | });
52 |
53 | server.listen(3000); // Start the server on port 3000
54 |
55 | ```
56 |
57 |
58 | ## ⭐ What developer Make with Node Js?
59 |
60 |
61 |
62 |
63 |
64 | First request is coming from client like browser, Android, IOS etc then that request is send to server and then server connect to the database and file server and get the data and send it to the client.
65 |
66 |
67 | - Developers Make API with Node js
68 | > API in simple words is a set of rules that allow two software programs to communicate with each other. When you send a request to a server, the server sends back a response. The request and response are both in the form of an API call. For example, when you search for a product on Amazon, the server sends back a response that contains the product information. This response is an API call.
69 | - So we can connect Server with Client
70 | - Node can make API for web, Android and IOS etc.
71 | - Make can also make website
72 |
73 |
--------------------------------------------------------------------------------
/14. CRUD Operations/README.md:
--------------------------------------------------------------------------------
1 | ## ⭐ CRUD Operations
2 |
3 |
4 |
5 |
7 |
8 |
9 |
10 |
11 | What is CRUD ?
12 |
13 |
14 |
15 | CRUD stands for Create, Read, Update, and Delete. These are the basic operations that you can perform on data in a database.
16 |
17 | - Create: Create a new record in a database.
18 | - Read: Read an existing record from a database.
19 | - Update: Update an existing record in a database.
20 | - Delete: Delete an existing record from a database.
21 |
22 |
23 |
24 | ### 📝 Create
25 |
26 | 1. When we work with the file system module, we have to use the `fs` module.
27 | 2. `fs.writeFileSync('hello.txt', 'Hello from Node.js');` will create a file named `hello.txt` and write the text `Hello from Node.js` to it.
28 | 3. But if I want to make this file inside a folder named `crud`, then I have to write `fs.writeFileSync('crud/hello.txt', 'Hello from Node.js');`.
29 | or
30 | You can use path module to create a file inside a folder.
31 | ```js
32 | // Import the path module to manipulate file and directory paths
33 | const path = require('path');
34 | // Import the fs module to perform file system operations
35 | const fs = require('fs');
36 |
37 | // Use the path.join() method to combine the current directory (__dirname) and the name of the crud folder into a single path
38 | const dirPath = path.join(__dirname, 'crud');
39 | // Use a template literal to append the name of the hello.txt file to the dirPath variable and store the result in filePath
40 | const filePath = `${dirPath}/hello.txt`;
41 |
42 | // Use the fs.writeFileSync() method to create a new file at the filePath location and write a string of text to it
43 | fs.writeFileSync(filePath, 'Hello from Node.js');
44 | ```
45 |
46 | ### 📝 Read
47 |
48 | 1. To read a file, we can use the `fs.readFile()` method.
49 | 2. Use `readFile()` method to read the contents of the `hello.txt` file.
50 | ```js
51 | const path = require('path');
52 | const fs = require('fs');
53 | const dirPath = path.join(__dirname, 'crud');
54 | const filePath = `${dirPath}/hello.txt`;
55 | // Read
56 | fs.readFile(filePath,(err, data) => {
57 | console.log(data)
58 | });
59 | ```
60 | > You will get a result with a buffer ``. Here buffer is a temporary storage spot for a file while it is being transferred from one place to another.
61 | 3. To solve this you have to pass another parameter `utf-8` to the `readFile()` method.
62 | ```js
63 | const path = require('path');
64 | const fs = require('fs');
65 | const dirPath = path.join(__dirname, 'crud');
66 | const filePath = `${dirPath}/hello.txt`;
67 |
68 | //Read
69 | fs.readFile(filePath,`utf-8`,(err, data) => {
70 | console.log(data)
71 | });
72 | ```
73 | > we use `utf-8` to convert the buffer to a string.
74 |
75 | ### 📝 Update
76 | 1. To update a file, we can use the `fs.appendFile()` method.
77 |
78 | ```js
79 | // Update
80 | fs.appendFile(filePath, 'CodeXam', (err) => {
81 | if (err) throw err;
82 | console.log('The "data to append" was appended to file!');
83 | }
84 |
85 | );
86 |
87 | ```
88 |
89 | or
90 |
91 | ```js
92 | // Update
93 | fs.appendFile(filePath, 'CodeXam', (err) => {
94 | if(!err){
95 | console.log('The "data to append" was appended to file!');
96 | }
97 | });
98 | ```
99 |
100 | > This will append the text `CodeXam` to the end of the `hello.txt` file.
101 | > If you run the file `node index.js` again, you will see the text `CodeXam` again appended to the end of the `hello.txt` file (repeatedly).
102 |
103 | ### 📝 Rename
104 |
105 | 1. We can use the `fs.rename()` method to rename a file.
106 | ```js
107 | fs.rename(filePath, `${dirPath}/rename.txt`, (err) => {
108 | if (err) throw err;
109 | console.log('Rename complete!');
110 | }
111 |
112 | );
113 | ```
114 | - rename() method takes two parameters, the first is the path to the file you want to rename, and the second is the path to the new file name.
115 | - here filePath is the path to the file you want to rename and `${dirPath}/rename.txt` is the path to the new file name.
116 | > This will rename the `hello.txt` file to `rename.txt`.
117 | > If you run the file `node index.js` again, you will see the text `CodeXam` again appended to the end of the `rename.txt` file (repeatedly).
118 |
119 |
120 | ### 📝 Delete
121 |
122 | 1. To delete a file, we can use the `fs.unlinkSync()` method.
123 | ```js
124 | fs.unlinkSync(`${dirPath}/rename.txt`);
125 | ```
126 | - unlinkSync() method takes one parameter, the path to the file you want to delete.
127 | > This will delete the `rename.txt` file.
128 |
129 |
130 |
131 | A **Buffer** in Node.js can be thought of as a temporary storage spot for data. It's a way to work with binary data, which is data that is represented as a sequence of bytes. You can use it to read and write files, work with network data, and more.
132 |
133 | Here's an example: Let's say you want to download an image from the internet and save it to your computer. You can use a Buffer to temporarily store the image data while it's being downloaded and then save it to a file.
134 |
135 | ```javascript
136 | const https = require('https');
137 | const fs = require('fs');
138 |
139 | const url = 'https://example.com/image.jpg';
140 | const file = fs.createWriteStream('image.jpg');
141 |
142 | https.get(url, (response) => {
143 | response.pipe(file);
144 | });
145 | ```
146 |
147 | This code downloads an image from the specified URL and saves it to a file called `image.jpg`. The image data is temporarily stored in a Buffer while it's being downloaded and written to the file.
148 |
--------------------------------------------------------------------------------
/13. Listing Files with the File System Module/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | ## ⭐ Files Creation
5 |
6 |
7 |
10 |
11 |
12 |
13 |
14 |
15 |
16 | Problem Statement : Make files in a folder
17 |
18 |
19 | 1. Create a folder named `files` in the root directory of your project.
20 |
21 |
22 |
23 | making a simple file is very easy just use the fs module and call the writeFileSync method and pass the file name and the data you want to write in the file as the parameters.
24 |
25 | ```js
26 | const fs = require('fs');
27 | fs.writeFileSync('hello.txt', 'Hello World!');
28 | ```
29 |
30 |
31 | 2. Now do like this
32 | ```js
33 | const fs = require('fs');
34 | const path = require('path');
35 | const dirPath = path.join(__dirname, 'files');//__dirname will give the current directory name and files is the folder name
36 |
37 | //console.warn(dirPath);//this will print the path of the folder
38 |
39 | for (i = 0; i < 10; i++) {
40 |
41 | //fs.writeFileSync("hello.txt", "Hello World!");
42 | //this will create a file named hello.txt in the root directory and overwrite it if it already exists
43 | //So we need to add dirPath in the file name and make it dynamic like text1.txt,text2.txt,text3.txt etc
44 |
45 | fs.writeFileSync(dirPath + `/file${i}.txt`, `Hello World! ${i}`);
46 |
47 | //fs.writeFileSync(dirPath + `/file'+i+'.txt`, `Hello World!`+i);//this will also work
48 | }
49 | ```
50 |
51 | > Now run `node index.js` and check the `files` folder. You should see 10 files with the names `file0.txt` to `file9.txt` and the contents `Hello World! X`, where X is the current value of `i`.
52 |
53 |
54 |
55 |
56 | ### Code Explanation
57 |
58 | #### Step 1
59 | ```const fs = require('fs');```
60 | - The `fs` module is used to interact with the file system in Node.js.
61 |
62 | #### Step 2
63 | ```const path = require('path');```
64 | - The `path` module provides utilities for working with file and directory paths.
65 |
66 | #### Step 3
67 | ```const dirPath = path.join(__dirname, 'files');```
68 | - The `__dirname` variable is a special variable in Node.js that represents the directory name of the current module.
69 | - The `path.join()` method joins all given path segments together using the platform-specific separator as a delimiter, then normalizes the resulting path.
70 | - In this case, we're joining the current directory name with a subdirectory called "files".
71 |
72 | #### Step 4
73 | ```for (i = 0; i < 10; i++) {```
74 | - This is a `for` loop that will run 10 times.
75 |
76 | #### Step 5
77 | ```fs.writeFileSync(dirPath + `/file${i}.txt`, `Hello World! ${i}`);```
78 | - The `fs.writeFileSync()` method writes data to a file, replacing the file if it already exists.
79 | - In this case, we're writing a file to the "files" subdirectory with a filename of "fileX.txt", where X is the current value of `i`.
80 | - The contents of each file will be "Hello World! X", where X is the current value of `i`.
81 |
82 |
83 | Problem Statement : We need to see the files in the folder
84 |
85 |
86 | 3 . We are going to use readdir
87 |
88 | ```js
89 | fs.readdir(dirPath, (err, files) => {
90 | if (err) {
91 | console.error(err);
92 | return;
93 | }
94 | console.warn(files);
95 | });
96 | ```
97 |
98 | `Output`
99 |
100 | ```
101 | [ 'file0.txt',
102 | 'file1.txt',
103 | 'file2.txt',
104 | 'file3.txt',
105 | 'file4.txt',
106 | ]
107 | ```
108 |
109 |
110 |
111 | ### Code Explanation
112 |
113 | `fs.readdir(dirPath, (err, files)` - The `fs.readdir()` method reads the contents of a directory.
114 | - In this case, we're reading the contents of the "files" subdirectory.
115 | - The `files` parameter is an array of filenames in the directory.
116 | - The `err` parameter is an error object if an error occurred, or `null` if no error occurred
117 |
118 | `console.warn(files);` - This will print the array of filenames to the console.
119 |
120 |
121 |
122 |
123 |
124 |
125 | Problem Statement : We don't want to see the files in the array format
126 |
127 |
128 | 4. We are going to use the forEach method to iterate over the array and print the files
129 |
130 |
131 | forEach is a method that is used to iterate over an array.
132 |
133 | Syntax
134 | ```js
135 | arr.forEach(abc => {
136 | console.warn(abc);
137 | });
138 | ```
139 | or
140 | ```js
141 | arr.forEach((abc, index) => {
142 | console.warn(index, abc);
143 | });
144 | ```
145 |
146 |
147 |
148 |
149 |
150 | ```js
151 | fs.readdir(dirPath, (err, files) => {
152 | if (err) {
153 | console.error(err);
154 | return;
155 | }
156 | files.forEach(file => {
157 | console.warn(file);
158 | });
159 | });
160 | ```
161 | or
162 | ```js
163 | fs.readdir(dirPath, (err, files) => {
164 | if (err) {
165 | console.error(err);
166 | return;
167 | }
168 | files.forEach((file, index) => {
169 | console.warn(index, file);
170 | });
171 | });
172 | ```
173 |
174 | Output
175 | ```
176 | file0.txt
177 | file1.txt
178 | file2.txt
179 | file3.txt
180 | ...this will go on
181 | ```
182 |
183 |
184 | ### Code Explanation
185 |
186 | `files.forEach(file => {` - This is a `forEach` loop that will iterate over the array of filenames.
187 |
188 | `console.warn(file);` - This will print the filename to the console.
189 |
190 |
191 |
192 |
193 |
194 |
--------------------------------------------------------------------------------
/01. Introduction to Node js and the Course/README.md:
--------------------------------------------------------------------------------
1 | # [Website View](https://codexam.vercel.app/docs/node/node1)
2 |
3 | ## ⭐ What is Node.js?
4 |
5 |
6 |
7 |
10 |
11 |
12 | > In this article, for sure you will get many boring theory but trust me day by day you will fall in love with Node.js and you will be able to understand the theory behind it.
13 |
14 |
15 | - **Node is not a Language.**
16 | - **This is a Server Environment.**
17 | - **Node.js can connect with the database.**
18 | > Node.js can connect with the database because it is a server-side environment that can run JavaScript code and interact with various databases using drivers or modules. JavaScript, on the other hand, is mainly a client-side language that runs in the browser and cannot directly access the database for security reasons. To connect to the database from JavaScript, you need to use a backend service that can handle the database queries and send the results back to the browser.
19 |
20 | - Code and syntax are very similar to *JavaScript* But not exactly the same.
21 | - Node.js is free and open-source.
22 | - Node.js is a *JavaScript runtime* built on Chrome's V8 JavaScript engine.
23 |
24 | > Chrome's V8 JavaScript engine is an open-source JavaScript engine developed by the Google Chrome team. It is written in C++ and is used to execute JavaScript code in web browsers, Node.js, and other applications. V8 compiles JavaScript code into machine code directly, making it very fast and efficient. It also includes features such as just-in-time (JIT) compilation, garbage collection, and support for modern JavaScript features.
25 |
26 |
27 |
28 | ## ⭐ Why do we use Node?
29 |
30 |
31 |
32 | - Node.js is commonly used for building **APIs.**
33 | - Node.js allows for **seamless connection of databases** to web and mobile applications.
34 | - Node.js is **easy to understand** for those who know JavaScript.
35 | - Node.js is **incredibly fast for building APIs.**
36 | - Node.js and JavaScript can be used for **full-stack development.**
37 |
38 |
39 |
40 |
41 | ## ⭐ History of Node.js
42 |
43 |
44 |
45 |
46 | - **First Release:** Node was first released on May 27, 2009 by [Ryan Dahl](https://en.wikipedia.org/wiki/Ryan_Dahl), who was inspired by the event-driven and non-blocking I/O model of web browsers.
47 | - **Current Version:** The latest stable version of Node is 17.2.0, which was released on December 7, 2021. Node follows a semver (semantic versioning) scheme and releases a new major version every six months, with even-numbered versions receiving long-term support (LTS).
48 | - **Written in:** Node is mainly written in C, C++, and JavaScript. C and C++ are used to implement the core functionality and bindings to the V8 JavaScript engine, which executes the JavaScript code. JavaScript is used to write the standard library and most of the user-facing modules of Node.
49 |
50 | For more information, you can visit the [Node official website](https://nodejs.org/en/), the [Node GitHub repository](https://github.com/nodejs/node), or the [Node documentation](https://nodejs.org/en/docs/).
51 |
52 |
53 | ## ⭐ Is javascript and Node.js same?
54 |
55 |
56 |
57 | **JavaScript** and **Node.js** are related but not the same. Here are some differences and similarities between them:
58 |
59 | - **JavaScript and Node.js code syntax is same:** Both JavaScript and Node.js use the same syntax, which is based on the ECMAScript (ES) standard. This means that the basic rules and structures of writing code are the same for both.
60 | - **If you know JavaScript you can easily understand Node:** Knowing JavaScript can help you learn Node.js faster, as you are already familiar with the syntax and some of the built-in objects and methods. However, you still need to learn the specific features and modules of Node.js, such as the event loop, streams, buffers, etc.
61 | - **But both are not exactly the same:** JavaScript and Node.js are different in terms of their environments, capabilities, and purposes. JavaScript is a scripting language that can run on any platform that supports a JavaScript engine, such as web browsers, mobile devices, etc. Node.js is a software platform that runs JavaScript on the server-side, using the V8 engine.
62 | - **You can not connect JavaScript to DB:** JavaScript by itself cannot connect to a database, as it does not have any built-in modules or libraries for database access. You need to use a third-party framework or library, such as jQuery, Angular, React, etc., to communicate with a database using JavaScript.
63 | - **Node can connect with DB:** Node.js can connect to a database, as it has many modules and libraries that support various types of databases, such as MongoDB, MySQL, PostgreSQL, etc. You can use the native Node.js modules, such as `mysql` or `mongodb`, or use a third-party framework or library, such as `mongoose` or `sequelize`, to connect to a database using Node.js.
64 | - **Node.js runs on the server-side:** Node.js is designed to run on the server-side, which means that it can handle requests from clients, process data, perform computations, and send responses back to the clients. Node.js can also act as a web server, using modules such as `http` or `express`.
65 | - **JavaScript runs on the browser:** JavaScript is mainly used to run on the browser, which means that it can manipulate the HTML and CSS elements of a web page, add interactivity, validate user input, and communicate with the server using AJAX. JavaScript can also run on other platforms, such as mobile devices, using frameworks such as React Native or Ionic.
66 |
67 |
68 | ### Conclusion
69 | | Key Point | JavaScript | Node.js |
70 | |-----------|------------|---------|
71 | | Definition | A scripting language that can run on any platform that supports a JavaScript engine. | A software platform that runs JavaScript on the server-side, using the V8 engine. |
72 | | Database Connection | Cannot connect to a database by itself, needs a third-party framework or library. | Can connect to a database, has many modules and libraries that support various types of databases. |
73 | | Execution Environment | Mainly runs on the browser, can also run on other platforms using frameworks. | Runs on the server-side, can also act as a web server using modules. |
74 |
75 |
76 |
--------------------------------------------------------------------------------
/12. Taking Command Line Input/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | ## ⭐ Taking Command Line Input Using process.argv
6 |
7 |
8 |
11 |
12 |
13 |
14 |
15 | Problem Statement : Suppose you run `node index.js abc` in the terminal. You can't give input to the program.
16 |
17 |
18 | 1. In your index.js file, write the following code.
19 | ```js
20 | console.log(process.argv);
21 | ```
22 | - `process` - `process` is a global object in Node.js that provides information and control over the current Node.js process. It has several properties and methods, one of which is `argv`.
23 | - `argv` - argv(Argument Vector) is an array that holds the command-line arguments passed to the Node.js process when it was started. The first element of `argv` (at index 0) is the path to the Node.js executable, and the second element (at index 1) is the path to the JavaScript file being executed. Any additional arguments passed to the script will be stored in the subsequent elements of the array (starting from index 2).
24 |
25 | Example:
26 |
27 | Consider a script named `example.js` with the following content:
28 |
29 | ```javascript
30 | console.log(process.argv);
31 | ```
32 |
33 | If you run `node example.js arg1 arg2`, the output will be:
34 |
35 | ```
36 | [
37 | '/path/to/node',
38 | '/path/to/example.js',
39 | 'arg1',
40 | 'arg2'
41 | ]
42 | ```
43 |
44 | In this case, `arg1` and `arg2` are additional command-line arguments passed to the script. You can access them using `process.argv[2]` and `process.argv[3]`, respectively. This is useful for handling user input or configuring your script based on command-line options.
45 |
46 | 2. Now run `node index.js abc` in the terminal. You can see the output as follows:
47 |
48 | ```js
49 | [
50 | '/usr/local/bin/node',
51 | '/Users/yourname/Desktop/NodeJS/index.js',
52 | 'abc'
53 | ]
54 | ```
55 | > - Here first element is the path to the Node.js executable.
56 | > - Second element is the path to the JavaScript file being executed.
57 | > - Third element is the input that you have given.
58 |
59 | 3. Now, you can access the input using `process.argv[2]`. For example, if you want to print the input, you can write the following code:
60 |
61 | ```js
62 | console.log(process.argv[2]);
63 | ```
64 | 4. Now run `node index.js abc` in the terminal. You can see the output as follows:
65 |
66 | ```js
67 | abc
68 | ```
69 |
70 | ## ⭐ Creating a File Using writeFileSync()
71 |
72 |
73 |
74 | Problem Statement : Three inputs will be given to create a file. The second argument will be the file name. The third argument is the file's content.
75 |
76 |
77 | 1. First import the `fs` module.
78 | ```js
79 | const fs = require('fs');
80 | ```
81 | 2. We need to take the input from the command line. So, we will use `process.argv`. We will store the input in a variable.
82 | ```js
83 | const fileName = process.argv;
84 | ```
85 | 3. Now, we will create a file using the `fs` module. We will use the `writeFileSync` method. It takes two arguments. The first argument is the file name. The second argument is the content of the file.
86 | ```js
87 | fs.writeFileSync(fileName[2], fileName[3]);
88 | ```
89 | > - `writeFileSync` - The `writeFileSync` method is used to write data to a file, replacing the file if it already exists. The method takes two arguments. The first argument is the file name. The second argument is the content of the file.
90 | > - `fileName[2]` - It is the file name.
91 | > - `fileName[3]` - It is the content of the file.
92 | > - We don't use 0 and 1 index because 0 index is the path to the Node.js executable and 1 index is the path to the JavaScript file being executed.
93 |
94 | 4. Now, run `node index.js abc.txt "Hello World"` in the terminal.
95 | 5. Now, you can see that a file named `abc.txt` is created in the current directory. You can open the file and see the content.
96 | ```js
97 | Hello World
98 | ```
99 |
100 |
101 |
102 | ## ⭐ Remove and Add a File Using WriteFileSync & UnlinkSync
103 |
104 |
105 | Problem Statement : Now I want to remove the file and add the file.
106 |
107 |
108 | 1. First use `if statement` to check the command.
109 | ```js
110 | if (process.argv[2] == 'add') {
111 | // code
112 | }
113 | ```
114 | - Inside the `if statement`, we will use `writeFileSync` method to add the file.
115 | ```js
116 | const fs = require('fs');
117 |
118 | const fileName = process.argv;
119 |
120 | if (fileName[2] == 'add')
121 | {
122 | fs.writeFileSync(fileName[3], fileName[4]);
123 | }
124 | ```
125 |
126 | 2. else if statement to check the command.
127 | ```js
128 | else if (process.argv[2] == 'remove') {
129 | // code
130 | }
131 | ```
132 | - Inside the `else if statement`, we will use `unlinkSync` method to remove the file.
133 | ```js
134 | const fs = require('fs');
135 |
136 | const fileName = process.argv;
137 |
138 | if (fileName[2] == 'add')
139 | {
140 | fs.writeFileSync(fileName[3], fileName[4]);
141 | }
142 |
143 | else if (fileName[2] == 'remove')
144 |
145 | {
146 | fs.unlinkSync(fileName[3]);
147 | }
148 |
149 | ```
150 | 3. `else statement` to check the command.
151 |
152 | ```js
153 | else {
154 | // code
155 | }
156 | ```
157 | - Inside the `else statement`, we will use `console.log` method to print the message.
158 |
159 | ```js
160 | const fs = require("fs");
161 |
162 | const fileName = process.argv;
163 |
164 | if (fileName[2] == "add") {
165 | fs.writeFileSync(fileName[3], fileName[4]);
166 | } else if (fileName[2] == "remove") {
167 | fs.unlinkSync(fileName[3]);
168 | }
169 | else {
170 | console.log("Please enter a valid command");
171 | }
172 |
173 |
174 | ```
175 |
176 | 4. Now, run `node index.js add subham.txt "Hello Xam"` in the terminal.
177 |
178 | 5. Now, you can see that a file named `subham.txt` is created in the current directory. You can open the file and see the content.
179 |
180 | ```js
181 | Hello Xam
182 | ```
183 |
184 | 6. Now, run `node index.js remove subham.txt` in the terminal.
185 |
186 | 7. Now, you can see that a file named `subham.txt` is removed from the current directory.
187 |
--------------------------------------------------------------------------------
/22. Remove extension from URL/README.md:
--------------------------------------------------------------------------------
1 |
2 | ## ⭐ Remove Extension
3 |
4 | In the previous section, we learned how to render html static page using express static middleware to serve the static files from the public folder. In this section, we will learn how to remove the extension from the URL.
5 |
6 | ### What is the exact problem?
7 |
8 | The main problem is that we have to write the extension of the file in the URL. For example, if we want to access the index.html file, we have to write the URL as `http://localhost:3000/index.html`. But we want to access the index.html file using the URL `http://localhost:3000/index.`
9 |
10 |
11 | ### How to solve the problem?
12 |
13 | We simply use get method of express to render the html file. We will use the `res.sendFile()` method to render the html file. The `res.sendFile()` method takes the path of the file as the first argument.
14 |
15 | - Something like this:
16 | ```js
17 | app.get('/', (req, res) => {
18 | res.sendFile(path.join(__dirname, 'public', 'index.html'));
19 | });
20 | ```
21 | This code looks like this:
22 |
23 | ```js
24 | const express = require("express");
25 | const path = require("path");
26 |
27 | const app = express();
28 | const publicPath = path.join(__dirname, "public");
29 |
30 |
31 | // app.use(express.static(publicPath));//We don't use this
32 |
33 | //We use this instead of the above line
34 | app.get("/about", (req, res) => {
35 | res.sendFile(`${publicPath}/about.html`);
36 | });
37 |
38 | app.listen(5001);
39 | ```
40 | - Here "/about" is the path of the about.html file. We can use any path we want. For example, we can use "/about-us" instead of "/about" as the path of the about.html file.
41 |
42 | - Now, we can access the about.html file using the URL `http://localhost:5001/about`. We don't have to write the extension of the file in the URL.
43 |
44 | - We will use sendFile() method to render the html file. We don't use send() method to render the html file because send() method will send the html file as a string. But we want to send the html file as a file.
45 |
46 | - publicPath is the path of the public folder. We will use this path to render the html file.
47 | - and /about.html is the path of the about.html file. We will use this path to render the html file.
48 |
49 | #### If you want to add multiple endpoints, you can do it like this:
50 |
51 | ```js
52 | const express = require("express");
53 | const path = require("path");
54 |
55 | const app = express();
56 | const publicPath = path.join(__dirname, "public");
57 |
58 | app.get("/", (req, res) => {
59 | res.sendFile(`${publicPath}/about.html`);
60 | });
61 |
62 | app.get("/about", (req, res) => {
63 | res.sendFile(`${publicPath}/about.html`);
64 | });
65 |
66 | app.get("/contact", (req, res) => {
67 | res.sendFile(`${publicPath}/about.html`);
68 | });
69 |
70 | app.listen(5001);
71 | ```
72 | - Here, we have added three endpoints. We can add as many endpoints as we want.
73 |
74 |
75 | ## ⭐ Default Page
76 |
77 | Suppose user type wrong URL in the browser. For example, if user type `http://localhost:5001/abou` in the browser, then the browser will show the error message "Cannot GET /abou". We want to show the default page if the user type wrong URL in the browser.
78 |
79 | You can simply use `*` as the path of the default page. For example, if we want to show the default page if the user type wrong URL in the browser, then we can use `*` as the path of the default page.
80 |
81 | ```js
82 | const express = require("express");
83 | const path = require("path");
84 |
85 | const app = express();
86 | const publicPath = path.join(__dirname, "public");
87 |
88 | app.get("/", (req, res) => {
89 | res.sendFile(`${publicPath}/about.html`);
90 | });
91 |
92 | app.get("/about", (req, res) => {
93 | res.sendFile(`${publicPath}/about.html`);
94 | });
95 |
96 | app.get("/contact", (req, res) => {
97 | res.sendFile(`${publicPath}/about.html`);
98 | });
99 |
100 | //Default page
101 | app.get("*", (req, res) => {
102 | res.sendFile(`${publicPath}/about.html`);
103 | });
104 |
105 | app.listen(5001);
106 | ```
107 |
108 | - Now, if the user type wrong URL in the browser, then the browser will show the default page.
109 |
110 | ## ⭐ 404 Page
111 | - Go to public folder and create a new file called 404.html. This file will be our 404 page.
112 |
113 | ```html
114 |
115 |
116 |
117 |
118 | 404 Error - Page Not Found
119 |
159 |
160 |
161 |
162 |
163 |
404 Error - Page Not Found
164 |
Oops! Looks like the page you're trying to access doesn't exist.
165 |
Please check the URL and try again or go back to the homepage.
166 |
167 |
168 |
169 |
170 | ```
171 |
172 | Now in the index.js file, we will use same `*` as the path of the 404 page.
173 |
174 | ```js
175 | const express = require("express");
176 | const path = require("path");
177 |
178 | const app = express();
179 | const publicPath = path.join(__dirname, "public");
180 |
181 | app.get("/", (req, res) => {
182 | res.sendFile(`${publicPath}/about.html`);
183 | });
184 |
185 | app.get("/about", (req, res) => {
186 | res.sendFile(`${publicPath}/about.html`);
187 | });
188 |
189 | app.get("/contact", (req, res) => {
190 | res.sendFile(`${publicPath}/about.html`);
191 | });
192 |
193 | //Default page
194 | app.get("*", (req, res) => {
195 | res.sendFile(`${publicPath}/404.html`);
196 | });
197 |
198 | app.listen(5001);
199 | ```
200 | - This is how we can create a 404 page in express.
201 |
--------------------------------------------------------------------------------
/18. Introduction to Express/README.md:
--------------------------------------------------------------------------------
1 | ## ⭐ Introduction
2 |
3 |
4 |
7 |
8 |
9 |
10 |
11 | What is Express js ?
12 |
13 | Here's a simple way to think about the difference between Express.js and Node.js:
14 |
15 | - Express.js is like a house. It provides the structure and foundation that you need to build your web application.
16 | - Node.js is like the land that the house is built on. It provides the underlying infrastructure that allows Express.js to work.
17 | Without Express.js, you could still build a web application using Node.js, but it would be much more difficult and time-consuming. Express.js provides a number of features that make it much easier to build web applications, such as routing, templating, and error handling.
18 |
19 |
20 |
21 | ### What is Express.js?
22 | Express.js is a minimal and flexible NodeJS framework that provides a robust set of features for web applications like routing, sessions, caching, etc. It makes it easier to organize your application’s functionality with middleware and routing. It adds helpful utilities to Node.js’s HTTP objects. It facilitates the rendering of dynamic HTTP objects.
23 |
24 | ### How does it differ from Node.js?
25 | Node.js is a run-time environment for building server-side event-driven i/o application using javascript. Express.js is a framework based on node.js for building web-application using principles and approaches of node.js. In simpler terms, express.js makes handling API requests and server management easier than using only node.js.
26 |
27 | ### Benefits of using Express.js over Node.js
28 | - Provides a simpler interface to build your routes and then use them for handling requests made by the users.
29 | - Manages all the clutter that comes with setting up a server.
30 |
31 |
32 |
33 | ## ⭐ How to install Express js ?
34 |
35 |
36 | 1. **Install Node.js**: Before installing Express.js, you need to have Node.js installed on your computer. You can download the installer from the [official Node.js website](https://nodejs.org/en/download/).
37 |
38 | 2. **Create a new project**: Open your command line interface (CLI) and navigate to the directory where you want to create your new project. Then, run the following command to create a new directory for your project and navigate into it:
39 | ```
40 | mkdir myapp
41 | cd myapp
42 | ```
43 |
44 | 3. **Initialize your project**: In the `myapp` directory, run the following command to initialize your project and create a `package.json` file:
45 | ```
46 | npm init
47 | ```
48 | Follow the prompts to enter information about your project.
49 |
50 | 4. **Install Express.js**: In the `myapp` directory, run the following command to install Express.js and save it as a dependency in your `package.json` file:
51 | ```
52 | npm install express --save
53 | ```
54 |
55 | 5. **Create an Express.js app**: In the `myapp` directory, create a new file called `app.js`. This file will contain the code for your Express.js app. Here is some sample code to get you started:
56 | ```javascript
57 | // Require the express module, which is a web framework for Node.js
58 | const express = require('express');
59 | // Create an app object by calling the express function
60 | const app = express();
61 |
62 | // Define a route handler for the root path ('/')
63 | app.get('/', function (req, res) {
64 | // Use the res object to send a text message 'Hello World!' back to the client
65 | res.send('Hello World!');
66 | });
67 |
68 | // Tell the app to listen on port 3000
69 | app.listen(3000, function () {
70 | // Log a message 'Example app listening on port 3000!' to the terminal when the app starts listening
71 | console.log('Example app listening on port 3000!');
72 | });
73 | ```
74 |
75 | 6. **Run your app**: In the CLI, navigate to the `myapp` directory and run the following command to start your app:
76 | ```
77 | node app.js
78 | ```
79 | You should see a message that says "Example app listening on port 3000!".
80 |
81 | 7. **Test your app**: Open your web browser and navigate to `http://localhost:3000`. You should see a message that says "Hello World!".
82 |
83 | That's it! You have successfully installed Express.js and created a simple app.
84 |
85 |
86 |
87 | ## ⭐ Let's Create Basic
88 |
89 |
90 |
91 | 1. We need to import `express` module in our project.
92 | ```js
93 | const express = require("express")
94 | ```
95 | 2. We need to create a express app.
96 | ```js
97 | const app = express()
98 | ```
99 | 3. We need to create a route for our app.
100 | > - `get`, `post`, `put`, `delete` are the methods used to create a route for our app.
101 | > - get() method is used to create a route for our app and it takes two arguments first is the route and second is the callback function which will be executed when the route is accessed by the user.
102 | > - The get() method is used to create a route for a GET request. A GET request is a type of HTTP request that is used to retrieve data from a server. In this case, we are telling Express.js to return the message "Hello World!" when a user visits the URL /.
103 | > - The callback function takes two arguments first is the request object and second is the response object. The request object contains the information about the request made by the user and the response object contains the information about the response that will be sent to the user.
104 | > - send() method is used to send the response to the user.
105 |
106 | ```js
107 | //Home Page
108 | app.get(`/`, (req, res) => {
109 | res.send("This is our main Page");
110 | });
111 |
112 | //About Page
113 | app.get(`/about`, (req, res) => {
114 | res.send("This is our about Page");
115 | });
116 |
117 | //Contact Page
118 | app.get(`/contact`, (req, res) => {
119 | res.send("This is our contact Page");
120 | });
121 | ```
122 | 4. We need to listen to the port for our app.
123 | > - listen() method is used to listen to the port for our app and it takes two arguments first is the port number and second is the callback function which will be executed when the port is listening.
124 |
125 | ```js
126 | //Server
127 | app.listen(5001);
128 | ```
129 | > You can simply pass the port number as an argument to the listen() method.
130 |
131 | 5. Now we need to run our app.
132 | ```bash
133 | node app.js
134 | ```
135 | 6. Go to the browser
136 | - Now open your browser and type `http://localhost:5001` in the address bar and press enter you will see the message `This is our main Page` on the screen.
137 | - Now type `http://localhost:5001/about` in the address bar and press enter you will see the message `This is our about Page` on the screen.
138 | - Now type `http://localhost:5001/contact` in the address bar and press enter you will see the message `This is our contact Page` on the screen.
139 |
140 |
141 |
--------------------------------------------------------------------------------
/21. Make HTML Page/README.md:
--------------------------------------------------------------------------------
1 |
2 | ## ⭐ Make Html Pages
3 |
4 |
5 |
8 |
9 |
10 | ### ❗ HTML Setup
11 | 1. First Make a Folder name "public" in your project folder.
12 | 2. Inside the public folder make a file name "about.html" and write some html code.
13 | > You can write very basic html code or you can just simply copy the code from the below.
14 | ```js
15 |
16 |
17 |
18 |
19 | Neon Dark Theme HTML Page
20 |
21 |
22 |
23 |
24 |
25 |
34 |
35 |
36 |
37 |
38 |
39 |
Section 1
40 |
41 | Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc
42 | malesuada justo in risus bibendum aliquet.
43 |
44 |
45 |
46 |
47 |
Section 2
48 |
49 | Vivamus ac lacinia quam, vitae eleifend velit. Integer sit amet libero
50 | sit amet risus tristique mollis sed quis ipsum.
51 |
52 |
53 |
54 |
55 |
Section 3
56 |
57 | Donec feugiat dolor id sapien interdum, a ullamcorper nisl malesuada.
58 | Etiam nec feugiat leo.
59 |
60 |
61 |
62 |
63 |
66 |
67 |
68 | ```
69 |
70 | 3. Now if you want you can make a css file name "styles.css" and write some css code.
71 |
72 | ```css
73 | /* Body styles */
74 | body {
75 | background-color: #181818;
76 | color: #fff;
77 | font-family: Arial, sans-serif;
78 | font-size: 16px;
79 | line-height: 1.4;
80 | margin: 0;
81 | padding: 0;
82 | }
83 |
84 | /* Header styles */
85 | header {
86 | background-color: #181818;
87 | position: fixed;
88 | top: 0;
89 | left: 0;
90 | width: 100%;
91 | padding: 20px;
92 | z-index: 999;
93 | }
94 |
95 | .container {
96 | max-width: 960px;
97 | margin: 0 auto;
98 | }
99 |
100 | nav ul {
101 | list-style: none;
102 | margin: 0;
103 | padding: 0;
104 | display: flex;
105 | justify-content: space-between;
106 | align-items: center;
107 | }
108 |
109 | nav li {
110 | margin: 0 10px;
111 | }
112 |
113 | nav a {
114 | color: #fff;
115 | text-decoration: none;
116 | font-size: 18px;
117 | font-weight: bold;
118 | }
119 |
120 | /* Main styles */
121 | main {
122 | padding: 80px 0;
123 | }
124 |
125 | section {
126 | margin: 0 auto;
127 | max-width: 960px;
128 | padding: 40px;
129 | margin-bottom: 40px;
130 | }
131 |
132 | section h2 {
133 | font-size: 36px;
134 | margin: 0;
135 | margin-bottom: 20px;
136 | }
137 |
138 | section p {
139 | margin: 0;
140 | }
141 |
142 | .boxed {
143 | background-color: #222;
144 | box-shadow: 0 0 30px rgba(255, 255, 255, 0.1);
145 | border-radius: 10px;
146 | }
147 |
148 | /* Footer styles */
149 | footer {
150 | background-color: #181818;
151 | color: #fff;
152 | padding: 20px;
153 | text-align: center;
154 | }
155 |
156 | /* Neon color theme */
157 | a {
158 | color: #fff;
159 | text-decoration: none;
160 | }
161 |
162 | section h2,
163 | nav a:hover {
164 | color: #00ffea;
165 | text-shadow: 0 0 10px #00ffea;
166 | }
167 |
168 | .boxed:hover {
169 | transform: translateY(-10px);
170 | box-shadow: 0 10px 30px rgba(0, 255, 234, 0.3);
171 | }
172 |
173 | footer p {
174 | font-size: 14px;
175 | }
176 |
177 | @media screen and (max-width: 768px) {
178 | nav ul {
179 | flex-direction: column;
180 | }
181 | nav li {
182 | margin: 10px 0;
183 | }
184 |
185 | .container {
186 | padding: 0 20px;
187 | }
188 |
189 | main {
190 | padding: 20px 0;
191 | }
192 |
193 | section {
194 | padding: 20px;
195 | }
196 |
197 | section h2 {
198 | font-size: 24px;
199 | }
200 | }
201 | ```
202 | > It's not necessary to make a css file. You can write css code in the html file itself or you can simply skip this step.
203 |
204 | ### ❗ Node.js Setup
205 |
206 | 1. First inside open your `index.js` file and write the following code.
207 |
208 | ```js
209 | const express = require('express');
210 | const app = express();
211 |
212 | app.listen(5000);
213 | ```
214 | > This will call the express module and create a server on port 5000.
215 |
216 | 2. Now we want the path of the project folder so we will use __dirname. So write the following code.
217 |
218 | ```js
219 | const express = require('express');
220 | const app = express();
221 | // import path module
222 | const path = require('path');
223 |
224 | // set the path of the project folder
225 | //join the path of the project folder with the public folder
226 | const publicPath = path.join(__dirname, 'public');
227 |
228 | app.listen(5000);
229 | ```
230 | > __dirname is a global variable that gives the path of the project folder.
231 | > Join method joins the path of the project folder with the public folder.
232 | > If you want you can check the path by console logging it `console.log(publicPath);`
233 |
234 | 3. Now we will use the express static middleware to serve the static files. So write the following code.
235 |
236 | ```js
237 | const express = require('express');
238 | const app = express();
239 | const path = require('path');
240 |
241 | const publicPath = path.join(__dirname, 'public');
242 |
243 | // use the express static middleware to serve the static files
244 | app.use(express.static(publicPath));
245 |
246 | app.listen(5000);
247 | ```
248 | > Here use method is used to use the express static middleware means if you have any static files like html, css, js, images, etc. then you can use this middleware to serve the static files to the browser.
249 | > Use method takes the path of the public folder as an argument It is the function of the express module.
250 | > this app is coming from the express module because we have called the express module in the first line and stored it in the app variable.
251 |
252 | 4. Now open you browser and type `http://localhost:5000/about.html` and you will see the about page.
253 |
254 | 
255 |
256 | > If you want to add more pages then you can simply add more html files in the public folder and you can access them by typing `http://localhost:5000/nameofthefile.html`
257 |
258 |
259 |
260 |
261 |
262 |
--------------------------------------------------------------------------------
/03. Install and Set Up Node js/README.md:
--------------------------------------------------------------------------------
1 | # [Website View](https://codexam.vercel.app/docs/node/node3)
2 |
3 |
4 |
5 | ## ⭐ Install and Setup Node Js
6 |
7 |
8 |
9 |
12 |
13 |
14 |
15 |
16 | ### ⚡ Method 1: Using the Installer
17 |
18 | - 1. Visit the official Node.js website [here](https://nodejs.org/en/download/) and download the `.msi` file according to your system environment (32-bit or 64-bit).
19 | - 2. Run the Node.js setup wizard by double-clicking on the downloaded `.msi` file.
20 | - 3. Click **Next** to proceed through the setup wizard.
21 | - 4. Accept the terms in the License Agreement and click **Next**.
22 | - 5. Choose the destination folder where Node.js will be installed and click **Next**.
23 | - 6. Select the features you want to install and click **Next**.
24 | - 7. Click **Install** to start the installation process.
25 | - 8. Once the installation is complete, click **Finish**.
26 |
27 | ### ⚡ Method 2: Using a Package Manager
28 |
29 | - 1. Choose a package manager for your operating system from [this list](https://nodejs.org/en/download/package-manager/).
30 | - 2. Follow the instructions on the package manager's website to install Node.js. For example, for Windows, you can use Chocolatey, Scoop, or Winget.
31 |
32 | > Note: Some package managers may require additional steps or commands to install Node.js. Refer to the documentation of the package manager for more details.
33 |
34 | ### ⚡ Verifying the Installation
35 |
36 | To verify that Node.js is installed on your computer, open a terminal or command prompt and type `node -v`. This should display the version of Node.js that you have installed.
37 | ### ⚡ Updating Node.js
38 |
39 | To update Node.js to the latest version, you can either download the latest installer from the Node.js website and run it or use a package manager to update it.
40 | #### 📃 Using the Installer
41 |
42 | - 1. Visit the official Node.js website [here](https://nodejs.org/en/download/) and download the latest `.msi` file according to your system environment (32-bit or 64-bit).
43 | - 2. Run the Node.js setup wizard by double-clicking on the downloaded `.msi` file.
44 | - 3. Follow the same steps as when installing Node.js for the first time.
45 | #### 📃 Using a Package Manager
46 |
47 | Open a terminal or command prompt and type in the command to update Node.js using your package manager of choice. For example, for Windows using Chocolatey, you can type `choco upgrade nodejs`.
48 |
49 | > Note: The command to update Node.js may vary depending on your package manager. Refer to its documentation for more details.
50 |
51 | ### ⚡ Running a Node.js Program
52 |
53 | To run a Node.js program, you need to create a file with the `.js` extension and write some JavaScript code in it.
54 |
55 | - 1. Open a text editor such as Notepad or Visual Studio Code.
56 | - 2. Type in some JavaScript code such as `console.log('Hello, world!')`.
57 | - 3. Save the file with a `.js` extension such as `hello.js`.
58 | - 4. Open a terminal or command prompt and navigate to the directory where `hello.js` is located using `cd` command.
59 | - 5. Type `node hello.js` and press Enter.
60 |
61 | This should print `Hello, world!` to the terminal or command prompt.
62 |
63 |
64 |
65 |
66 |
67 |
68 | ## ⭐ Install NPM and Node
69 |
70 |
71 |
72 | ### What is NPM?
73 |
74 | > In simple words, `npm` controls the packages that you use in your `Node.js` projects. It lets you download and use free packages or modules from the npm registry, and also lets you publish and distribute your own packages or modules.
75 | - `npm` is a package manager for `Node.js`, which is a JavaScript runtime
76 |
77 | - `npm` lets you download and use free packages or modules from the npm registry
78 |
79 | - `npm` also lets you publish and distribute your own packages or modules
80 |
81 | - `npm` helps you manage the dependencies, versions, and scripts of your `Node.js` projects
82 |
83 | - `npm` is included when you install `Node.js` on your computer
84 |
85 |
86 |
87 |
88 |
89 |
90 | ## ⭐ Some IDE for Node Js
91 |
92 |
93 |
94 |
95 | ### 1. Visual Studio Code (VS Code)
96 | - **Key Features:** Debugging, IntelliSense, Git integration, extensions marketplace, integrated terminal, code snippets, built-in JavaScript/TypeScript support.
97 | - **Why Use It:** VS Code is a free, open-source, and highly customizable IDE that supports a wide range of programming languages including Node.js. It has a large and active community that creates and maintains a variety of extensions, making it a powerful tool for Node.js developers.
98 | - **Download Link:** [Download VS Code](https://code.visualstudio.com/download)
99 | - **Note:** VS Code also has a Node.js extension that provides additional features like auto-completion, debugging, and npm integration.
100 |
101 | ### 2. WebStorm
102 | - **Key Features:** Refactoring, debugging, testing, code analysis, intelligent code completion, Git integration, integrated terminal.
103 | - **Why Use It:** WebStorm is a powerful and user-friendly IDE that provides a range of features specifically designed for Node.js development. It also has built-in support for various web technologies like HTML, CSS, and JavaScript, making it a great choice for full-stack developers.
104 | - **Download Link:** [Download WebStorm](https://www.jetbrains.com/webstorm/download/)
105 | - **Note:** WebStorm is a paid IDE, but it offers a free trial period.
106 |
107 | ### 3. Atom
108 | - **Key Features:** Customizable UI, Git integration, package manager, built-in JavaScript/Node.js support, multiple panes, code snippets.
109 | - **Why Use It:** Atom is a free and open-source text editor that is highly customizable and has a thriving community of developers who contribute to its ecosystem of packages and plugins. It also has built-in support for Node.js, making it a great choice for Node.js developers.
110 | - **Download Link:** [Download Atom](https://atom.io/)
111 | - **Note:** Atom has a slower performance compared to other IDEs, especially when dealing with large projects.
112 |
113 | ### 4. Sublime Text
114 | - **Key Features:** Multiple cursors, command palette, powerful search and replace, code snippets, Git integration, customizability.
115 | - **Why Use It:** Sublime Text is a lightweight and fast text editor that is highly customizable and has a large library of plugins and packages. It has built-in support for JavaScript and Node.js, making it a popular choice among web developers.
116 | - **Download Link:** [Download Sublime Text](https://www.sublimetext.com/)
117 | - **Note:** Sublime Text is a paid text editor, but it offers a free trial period.
118 |
119 |
120 | | IDE/Text Editor | Pros | Cons |
121 | | --- | --- | --- |
122 | | Visual Studio Code | • Free and open source • Large and active community • Customizable UI • Builtin support for JavaScript/Node.js | • Can be resource intensive • Some features require extensions • Limited support for larger projects |
123 | | WebStorm | • Builtin support for Node.js development • Intuitive and user friendly interface • Great for full stack development • Robust set of features | • Paid IDE • Can be resource intensive |
124 | | Atom | • Free and open source • Highly customizable • Large library of plugins and packages • Builtin support for Node.js | • Slower performance compared to other IDEs • Some features require packages • Limited support for larger projects |
125 | | Sublime Text | • Lightweight and fast • Highly customizable • Large library of plugins and packages • Builtin support for JavaScript/Node.js | • Paid text editor • Limited support for larger projects • Some features require packages |
126 |
127 |
128 |
129 |
--------------------------------------------------------------------------------
/20. Html Render/README.md:
--------------------------------------------------------------------------------
1 |
2 | ## ⭐ Let's render HTML
3 |
4 |
5 |
8 |
9 |
10 |
11 | ```js
12 | const express = require("express");
13 | const app = express();
14 | //Home Page
15 | app.get(`/`, (req, res) => {
16 | console.log("Data send by the client: ", req.query.id);
17 | res.send("This is our main Page");
18 | });
19 | //Server
20 | app.listen(5001);
21 | ```
22 |
23 | 1 You can simply add `h1` tag to the `res.send()` function to render HTML pages.
24 |
25 | ```js
26 | const express = require("express");
27 | const app = express();
28 | //Home Page
29 | app.get(`/`, (req, res) => {
30 | console.log("Data send by the client: ", req.query.id);
31 | res.send("
This is our main Page
");
32 | });
33 | //Server
34 | app.listen(5001);
35 | ```
36 |
37 |
38 |
39 | 2. Suppose you want take an input from the user on the about page you can do it like this
40 |
41 | ```js
42 | const express = require("express");
43 | const app = express();
44 |
45 | //Home Page
46 | app.get(`/`, (req, res) => {
47 | console.log("Data send by the client: ", req.query.id);
48 | res.send("
This is our main Page
");
49 | });
50 |
51 | //About Page
52 | app.get(`/about`, (req, res) => {
53 | res.send(`
54 |
55 |
56 | `);
57 | });
58 |
59 | //Server
60 | app.listen(5001);
61 | ```
62 |
63 | 3. If you want to show json data on the `data` page you can do it like this
64 |
65 | ```js
66 | const express = require("express");
67 | const app = express();
68 |
69 | //Home Page
70 | app.get(`/`, (req, res) => {
71 | console.log("Data send by the client: ", req.query.id);
72 | res.send("
About");
154 | });
155 |
156 | //About Page
157 | app.get(`/about`, (req, res) => {
158 | res.send(`
159 |
160 |
161 | Home
162 | `);
163 | });
164 |
165 | //Data Page
166 |
167 | app.get(`/data`, (req, res) => {
168 | res.send([
169 | {
170 | name: "Subham Maity",
171 | age: 16,
172 | country: "India",
173 | },
174 | {
175 | name: "Raj Sharma",
176 | age: 17,
177 | country: "India",
178 | },
179 | ]);
180 | });
181 |
182 | //Server
183 |
184 | app.listen(5001);
185 |
186 | ```
187 | > Use `href` attribute to jump from one page to another page
188 |
189 |
190 | 5. If you want to set parameters in the url
191 | > suppose you hit `localhost:5001/about?name=Subham` and you want to get the name of the user in the input field you can do it like this
192 |
193 |
194 | ```js
195 |
196 | const express = require("express");
197 | const app = express();
198 |
199 | //Home Page
200 | app.get(`/`, (req, res) => {
201 | console.log("Data send by the client: ", req.query.id);
202 | res.send("
This is our main Page
About");
203 | });
204 |
205 | //About Page
206 | app.get(`/about`, (req, res) => {
207 | res.send(`
208 |
209 |
210 | Home
211 | `);
212 | });
213 |
214 | //Data Page
215 |
216 | app.get(`/data`, (req, res) => {
217 | res.send([
218 | {
219 | name: "Subham Maity",
220 | age: 16,
221 | country: "India",
222 | },
223 | {
224 | name: "Raj Sharma",
225 | age: 17,
226 | country: "India",
227 | },
228 | ]);
229 | });
230 |
231 | //Server
232 |
233 | app.listen(5001);
234 |
235 | ```
236 | > Use `req.query` to get the parameters from the url and use `value` attribute to set the value of the input field to the parameter value
237 | > You can learn more about `req.query` [here](https://expressjs.com/en/api.html#req.query)
238 |
239 | ### ⚡ query
240 |
241 | **Step 1: Making a GET request with query string parameters**
242 | - When you make a GET request to a URL that includes query string parameters, the parameters are included in the URL after a `?` symbol. For example, if you want to make a GET request to the `/about` page and pass the `name` parameter with the value `"Subham"`, the URL would be `localhost:5001/about?name=Subham`.
243 | - In this example, the query string is `name=Subham`.
244 |
245 | **Step 2: Accessing query string parameters in Express.js**
246 | - In an Express.js application, you can access the query string parameters of a GET request using the `req.query` property. This property is an object that contains the query string parameters as key-value pairs.
247 | - In our example, if you make a GET request to `localhost:5001/about?name=Subham`, the `req.query` object will contain the property `name` with the value `"Subham"`.
248 |
249 | **Step 3: Using query string parameters to set the value of an input field**
250 | - You can use the value of a query string parameter to set the value of an input field on your page. To do this, you need to set the `value` attribute of the input field to the value of the query string parameter.
251 | - In our example, if you want to set the value of an input field on the `/about` page to the value of the `name` parameter passed in the URL, you can do this by setting the `value` attribute of the input field to `${req.query.name}`.
252 |
253 | Here's an example that shows how this works:
254 |
255 | ```js
256 | app.get(`/about`, (req, res) => {
257 | res.send(`
258 |
259 |
260 | Home
261 | `);
262 | });
263 | ```
264 |
265 | In this code, we have an Express.js route for handling GET requests to the `/about` page. When a GET request is made to this page, we send back an HTML response that includes an input field. The `value` attribute of this input field is set to `${req.query.name}`, which means that it will be pre-populated with the value of the `name` parameter passed in the URL.
266 |
267 |
268 |
269 |
270 |
271 |
272 |
--------------------------------------------------------------------------------
/08. Package.json/README.md:
--------------------------------------------------------------------------------
1 | ## ⭐ Understanding Package.json
2 |
3 |
4 |
16 |
17 | The package.json file is the heart of any Node.js project. It is the place where we define the project's metadata, including its name, version, description, main entry point, dependencies, and more. It is also where we define the scripts that we can run using the npm run command.
18 |
19 |
20 |
21 |
22 | > - In simple words, the package.json file saves all the information about the project and its dependencies. It also contains the scripts that we can run using the npm run command.
23 | > - If you want to recreate the project on another machine, you can use the package.json file to install all the dependencies and run the project.
24 |
25 |
26 | *********
27 |
28 |
29 | Let's Make a Package.json
30 |
31 |
32 | 1. Open the terminal and navigate to the project folder.
33 | 2. Run the following command to create a package.json file.
34 | ```bash
35 | npm init
36 | ```
37 | 3. Now you will see a series of questions in the terminal. You can press the Enter key to accept the default value for each question. The default values are shown in square brackets.
38 |
39 | ```bash
40 | This utility will walk you through creating a package.json file.
41 | It only covers the most common items, and tries to guess sensible defaults.
42 |
43 | See `npm help init` for definitive documentation on these fields
44 | and exactly what they do.
45 |
46 | Use `npm install ` afterwards to install a package and
47 | save it as a dependency in the package.json file.
48 |
49 | Press ^C at any time to quit.
50 |
51 | package name: (node-js-full-stack-tutorial)
52 | version: (1.0.0)
53 | description: Node.js Full Stack Tutorial
54 | entry point: (index.js)
55 | test command:
56 | git repository:
57 | keywords:
58 | author: Subham Maity
59 | license: (ISC)
60 |
61 | Is this OK? (yes)
62 | ```
63 |
64 | 4. After answering all the questions, you will get a file named package.json in the project folder. The package.json file will look like this:
65 |
66 | ```json filename="package.json"
67 |
68 | {
69 | "name": "node-js-full-stack-tutorial",
70 | "version": "1.0.0",
71 | "description": "Node.js Full Stack Tutorial",
72 | "main": "index.js",
73 | "scripts": {
74 | "test": "echo \"Error: no test specified\" && exit 1"
75 | },
76 | "author": "Subham Maity",
77 | "license": "ISC"
78 | }
79 | ```
80 |
81 | > - The name field is the name of the project.
82 | > - The version field is the version of the project.
83 | > - The description field is the description of the project.
84 | > - The main field is the entry point of the project meaning the file that will be executed when we run the project.
85 | > - The scripts field is an object that contains the scripts that we can run using the npm run command.
86 | > - The author field is the name of the author of the project.
87 | > - The license field is the license of the project.
88 |
89 | *********
90 |
91 | How to Install Additional Dependencies
92 |
93 | 1. Open the terminal and navigate to the project folder.
94 | 2. Let's suppose we want to install `colorful console` so search on google `colorful console` and click on the first [link](https://www.npmjs.com/package/colors).
95 | 3. Copy the command `npm install colors` and paste it in the terminal.
96 | 4. When you hit enter you will see the following changes
97 | - Create a new folder named node_modules in the project folder.
98 | - Create a new file named package-lock.json in the project folder.
99 | - Update the package.json file.
100 |
101 | ```json filename="package.json" /"colors": "^1.4.0"/
102 | {
103 | "name": "node-js-full-stack-tutorial",
104 | "version": "1.0.0",
105 | "description": "Node.js Full Stack Tutorial",
106 | "main": "index.js",
107 | "scripts": {
108 | "test": "echo \"Error: no test specified\" && exit 1"
109 | },
110 | "author": "Subham Maity",
111 | "license": "ISC",
112 | "dependencies": {
113 | "colors": "^1.4.0"
114 | }
115 | }
116 | ```
117 | - colors is the name of the package that we installed and ^1.4.0 is the version of the package that we installed.
118 |
119 | Let install another package `simple logs` and see what happens.
120 |
121 | ```bash
122 | npm install simple-logs
123 | ```
124 |
125 |
126 | > Now if you open node_modules folder you will see two folders named colors and simple-logs even you can see another folders because these two packages have their own dependencies.
127 |
128 |
129 | *********
130 |
131 | What is package-lock.json
132 |
133 |
134 | The package-lock.json file is automatically generated for any operations where npm modifies either the node_modules tree, or package.json. It describes the exact tree that was generated, such that subsequent installs are able to generate identical trees, regardless of intermediate dependency updates.
135 |
136 |
137 |
138 |
139 |
140 |
141 |
142 |
143 |
144 |
145 |
146 | ```json filename="package-lock.json"
147 |
148 | {
149 | "name": "node-js-full-stack-tutorial",
150 | "version": "1.0.0",
151 | "lockfileVersion": 3,
152 | "requires": true,
153 | "packages": {
154 | "": {
155 | "name": "node-js-full-stack-tutorial",
156 | "version": "1.0.0",
157 | "license": "ISC",
158 | "dependencies": {
159 | "colors": "^1.4.0",
160 | "simple-logs": "^0.2.11"
161 | }
162 | },
163 | "node_modules/colors": {
164 | "version": "1.4.0",
165 | "resolved": "https://registry.npmjs.org/colors/-/colors-1.4.0.tgz",
166 | "integrity": "sha512-a+UqTh4kgZg/SlGvfbzDHpgRu7AAQOmmqRHJnxhRZICKFUT91brVhNNt58CMWU9PsBbv3PDCZUHbVxuDiH2mtA==",
167 | "engines": {
168 | "node": ">=0.1.90"
169 | }
170 | },
171 | "node_modules/simple-logs": {
172 | "version": "0.2.11",
173 | "resolved": "https://registry.npmjs.org/simple-logs/-/simple-logs-0.2.11.tgz",
174 | "integrity": "sha512-xByfJr26EY78A85FsGOHTovHrq3Tedo2bURLynhL9zHNvTo5H2X210q4HN3eY9QJVmpNMpHOBZytLVAmHgrUlg==",
175 | "engines": {
176 | "node": ">=0.6"
177 | }
178 | }
179 | }
180 | }
181 |
182 | ```
183 |
184 |
185 |
186 | > If you delete the node_modules folder and package-lock.json file , this will not affect your project because when you run the project npm will automatically install the dependencies.
187 |
188 | > -⚡ But if you delete the package.json file then you will not be able to run the project because npm will not know which dependencies to install.
189 |
190 |
191 | *********
192 |
193 | How to Uninstall Dependencies
194 |
195 |
196 | To uninstall a package, you can use the npm uninstall command. For example, to uninstall the colors package, you can run the following command:
197 | ```bash
198 | npm uninstall colors
199 | ```
200 |
201 |
202 | *********
203 |
204 | How to Update Dependencies
205 |
206 |
207 | To update a package, you can use the npm update command. For example, to update the colors package, you can run the following command:
208 | ```bash
209 | npm update colors
210 | ```
211 |
212 |
213 |
214 | *********
215 |
216 | How to Install Specific Version of a Package
217 |
218 |
219 |
220 | To install a specific version of a package, you can use the npm install command with the @ character followed by the version number. For example, to install the colors package version 1.3.3, you can run the following command:
221 |
222 | ```bash
223 | npm install colors@1.3.3
224 | ```
225 |
226 |
227 |
228 | *********
229 |
230 | Let's use colors package
231 |
232 |
233 |
234 | 1. Open the index.js file and import the colors package at the top of the file like this:
235 |
236 | ```js filename="index.js"
237 |
238 | const colors = require('colors');
239 | ```
240 |
241 | 2. Now let's use the colors package to print some colored text in the console. Replace the code in the index.js file with the following code:
242 |
243 | ```js filename="index.js"
244 | const colors = require('colors');
245 |
246 | //This will print the text in red
247 | console.log('Hello World'.rainbow);
248 |
249 | //This will print the text in blue
250 | console.log('Hello World'.blue);
251 |
252 | //This will print the text in yellow
253 | console.log('Hello World'.yellow);
254 |
255 | //This will print the text in green
256 | console.log('Hello World'.green);
257 |
258 | //This will print the text in magenta
259 | console.log('Hello World'.magenta);
260 |
261 | //This will print the text in cyan
262 | console.log('Hello World'.cyan);
263 |
264 | //This will print the text in white
265 | console.log('Hello World'.white);
266 |
267 | //This will print the text in gray
268 | console.log('Hello World'.gray);
269 | ```
270 |
271 | 3. Now run the project using the following command:
272 |
273 | ```bash
274 | npm start
275 | ```
276 |
277 | 4. You will see hello world printed in different colors in the console.
278 |
279 |
280 | > Node JS is single threaded. This means that it can only execute one task at a time. This is why Node JS is very fast and efficient.We will learn more about Node JS in the next chapter.
281 |
282 |
283 |
284 |
--------------------------------------------------------------------------------
/19. Routing with Express.js(req , res)/README.md:
--------------------------------------------------------------------------------
1 | ## ⭐ Explain Server & Client in Detail
2 |
3 |
4 |
5 |
8 |
9 |
10 |
11 |
12 | 1. A user sends an HTTP request using either the GET or POST method to a server.
13 | 2. The server receives the request and processes it.
14 | 3. If the request is a GET request, the server retrieves data from the database based on the parameters specified in the request.
15 | 4. If the request is a POST request, the server stores the data sent in the request into the database.
16 | 5. Once the data is retrieved or stored, it is formatted into JSON format (if necessary) and sent back to the client in an HTTP response.
17 | 6. The client receives the HTTP response and processes the JSON data (if any) to display it to the user.
18 |
19 |
20 | *********
21 |
22 |
23 | ### 📃Additional Information
24 |
25 |
26 |
27 |
28 |
29 | #### ⚡ Overview of how each HTTP method works:
30 |
31 | - **GET**: The GET method is used to retrieve data from a server. When a GET request is sent to a server, the server retrieves data from the database based on the parameters specified in the request and sends it back to the client in an HTTP response.
32 |
33 | - **POST**: The POST method is used to send data to a server to be processed. When a POST request is sent to a server, the server processes the data sent in the request and stores it in the database.
34 |
35 | - **PUT**: The PUT method is used to update an existing resource on the server. When a PUT request is sent to a server, the server updates the specified resource with the data sent in the request.
36 |
37 | - **PATCH**: The PATCH method is similar to the PUT method but is used to apply partial updates to a resource on the server. When a PATCH request is sent to a server, the server applies the specified changes to the resource.
38 |
39 | - **DELETE**: The DELETE method is used to delete a resource on the server. When a DELETE request is sent to a server, the server deletes the specified resource.
40 |
41 | - **COPY**: The COPY method is used to create a copy of a resource on the server. When a COPY request is sent to a server, the server creates a copy of the specified resource.
42 |
43 | - **HEAD**: The HEAD method is similar to the GET method but is used to retrieve only the headers of a resource on the server. When a HEAD request is sent to a server, the server returns only the headers of the specified resource in an HTTP response.
44 |
45 | - **OPTIONS**: The OPTIONS method is used to retrieve information about the communication options available for a resource on the server. When an OPTIONS request is sent to a server, the server returns information about the available communication options for the specified resource in an HTTP response.
46 |
47 | - **LINK**: The LINK method is used to establish relationships between resources on the server. When a LINK request is sent to a server, the server establishes relationships between resources as specified in the request.
48 |
49 | - **UNLINK**: The UNLINK method is used to remove relationships between resources on the server. When an UNLINK request is sent to a server, the server removes relationships between resources as specified in the request.
50 |
51 | - **PURGE**: The PURGE method is used to remove cached copies of resources on proxy servers. When a PURGE request is sent to a proxy server, it removes cached copies of resources as specified in the request.
52 |
53 | - **LOCK**: The LOCK method is used to lock resources on WebDAV servers. When a LOCK request is sent to a WebDAV server, it locks resources as specified in the request.
54 |
55 | - **UNLOCK**: The UNLOCK method is used to unlock resources on WebDAV servers. When an UNLOCK request is sent to a WebDAV server, it unlocks resources as specified in the request.
56 |
57 | - **PROPFIND**: The PROPFIND method is used on WebDAV servers to retrieve properties of resources. When a PROPFIND request is sent to a WebDAV server, it returns properties of resources as specified in the request.
58 |
59 | - **VIEW**: The VIEW method does not exist in standard HTTP methods and may be specific to certain systems or applications.
60 |
61 |
62 |
63 |
64 |
65 |
66 | #### ⚡ Summary of the HTTP request and response process.
67 |
68 | - The HTTP method is used to indicate the type of request being made. The most common methods are GET, POST, PUT, and DELETE.
69 | - The HTTP headers are used to provide additional information about the request. For example, the Content-Type header indicates the type of data being sent in the request body.
70 | - The HTTP status code is used to indicate the success or failure of the request. The most common status codes are 200 (OK), 400 (Bad Request), and 500 (Internal Server Error).
71 | - The HTTP body is used to send data to the server. The data can be in any format, but JSON is a common format.
72 | - The JSON data is formatted into a JavaScript object. The object can contain any type of data, but it is often used to store data in a key-value format.
73 | - The client receives the HTTP response and processes the JSON data (if any) to display it to the user. The JSON data can be displayed in a variety of ways, but it is often used to create web pages, images, or files.
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 | ## ⭐ Request and Response
83 |
84 |
85 |
86 | ### **What are req and res?**
87 |
88 | - req and res are short names for `request` and `response`.
89 | - They are `objects` that help us communicate with the client using HTTP.
90 | - HTTP is a protocol that lets the `client and the server` exchange data over the internet.
91 |
92 | ### **What is the request object (req)?**
93 |
94 | The request object contains information about what the client wants from the server.
95 | - Some of the information in the request object are:
96 | - **The `URL`**: the address of the resource that `the client wants to access`.
97 |
98 | - **The `method`**: the action that the client wants to perform, such as `GET`, `POST`, `PUT`, `DELETE`, etc.
99 |
100 | - **The `headers`**: additional information about the request, such as the `content type`, the `language`, the `authorization`, etc.
101 |
102 | - **The `query string`**: optional data that is added to the URL after a question mark ``(?)``, such as /?name=John&age=25.
103 | - **The `parameters`**: optional data that is added to the URL as placeholders, such as /user/:id, where ``id`` can be any value.
104 | - **The `body`**: optional data that is sent along with the request, usually in a form or a `JSON format`.
105 | - The request object also has methods that let us check or modify the request, such as:
106 | - **`req.accepts ()`**: checks what kind of data the client can receive, such as `text, HTML, JSON`, etc.
107 | - **`req.is ()`**: checks what kind of data the client has sent, such as `text/plain, application/json`, etc.
108 | - **`req.get ()`**: gets a specific header from the request, such as `req.get ('content-type')`.
109 | - **`req.set ()`**: sets a specific header for the request, such as `req.set ('content-type', 'application/json')`.
110 |
111 |
112 | ************
113 |
114 |
115 | ### **What is the response object (res)?**
116 |
117 | The response object contains methods and properties to send back a response to the client.
118 | - Some of the methods and properties in the response object are:
119 | - `res.send ()`: sends a `simple message to the client`, such as res.send ('Hello World').
120 | - `res.json ()`: sends a `JSON object to the client`, such as res.json ```({name: 'John', age: 25}).```
121 | - `res.render ()`: `renders a view template to the client`, such as res.render ```('index', {title: 'Home Page'}).```
122 | - `res.status ()`: sets the status code for the response, such as `res.status (200) for success` or `res.status (404) for not found`.
123 | - `res.set ()`: `sets a specific header` for the response, such as `res.set ('content-type', 'text/plain')`.
124 | - `res.cookie ()`: sets a cookie for the response, such as `res.cookie ('name', 'John')`.
125 | - `res.sendFile ()`: sends a file to the client, such as `res.sendFile ('/path/to/file.jpg')`.
126 | - The response object also has properties that let us access or modify the response, such as:
127 | - `res.statusCode`: gets or sets the status code for the response, such as `res.statusCode = 200` or `console.log (res.statusCode)`.
128 | - `res.headersSent`: checks if the headers have been sent to the client, such as if `(res.headersSent)` ```{ // do something }.```
129 | - `res.locals`: stores local variables that are accessible within the view template, such as `res.locals.title = 'Home Page'`.
130 |
131 |
132 | *************
133 |
134 |
135 | ### **How do we use req and res in Express.js?**
136 |
137 | - Express.js is a web framework for Node.js that makes it easier to create web applications using HTTP.
138 | - In Express.js, we use `req` and `res` as parameters in a callback function that handles a specific route or middleware.
139 | - A route is a part of the URL that tells us what to do when a request is made. A middleware is a function that can change or add something to the request or response before or after a route is handled.
140 |
141 |
142 | *************
143 |
144 |
145 | **Example of using req and res in Express.js**
146 |
147 | In this example, we will use your code to show how req and res work in Express.js.
148 |
149 | ```js
150 | const express = require("express");
151 | const app = express();
152 |
153 | //Home Page
154 | app.get(`/`, (req, res) => {
155 | console.log("Data send by the client: ", req.query.id);
156 | res.send("This is our main Page");
157 | });
158 |
159 | //Server
160 | app.listen(5001);
161 | ```
162 |
163 | 1. We do
164 | ```js
165 | const express = require("express");
166 | ```
167 | > This line imports the express module using the require () function and stores it in a variable called express.
168 | 2. Then we do
169 | ```js
170 | const app = express();
171 | ```
172 | > This line creates an Express application using the express () function and stores it in a variable called app.
173 |
174 | ```js
175 | app.get(`/`, (req, res) => {
176 | console.log("Data send by the client: ", req.query.id);
177 | res.send("This is our main Page");
178 | });
179 | ```
180 | > - This line defines a route for the home page using app.get (). This means that whenever a client makes a GET request to the root path (/), the callback function will be executed. The callback function takes two arguments: req and res.
181 | > - The req argument represents the request object that contains information about the client's request. In this callback function, we use console.log () to print the value of req.query.id to the terminal. This means that if the client sends a request like /?id=123, we will see 123 in the terminal. The req.query property contains an object of key-value pairs that are added to the URL after a question mark (?).
182 | > - The res argument represents the response object that contains methods and properties to send back a response to the client. In this callback function, we use res.send () to send a message "This is our main Page" back to the client. This means that the client will see this message in their browser or other HTTP client. The res.send () method can send data in different formats, such as plain text, HTML, JSON, etc.
183 |
184 | 3. This line starts the server and listens for incoming requests on port 5001. This means that our application will be accessible at http://localhost:5001/.
185 |
186 | ```js
187 | app.listen(5001);
188 | ```
189 |
190 | 
191 |
192 |
193 |
194 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Node.js Tutorial 🚀
2 |
3 |
4 |
5 | Learn Node.js in less than 2 months with just 15 minutes of daily practice! 💪 This tutorial is perfect for beginners who want to become Node.js masters. You'll learn everything from the basics of Node.js to advanced topics like **asynchronous programming**, **modules**, **package management**, **web frameworks**, and more. Along the way, you'll build several projects including a **command-line interface**, a **RESTful API**, and a **real-time chat app**. If you have any doubts or questions, feel free to create an issue or comment in the feedback section. By the end of this tutorial, you'll have the skills and confidence to create your own server-side applications using Node.js. 🎉🎉🎉
6 |
7 | 
8 |
9 | ## Content List for *NodeJs* (2023) ▶️
10 | ### Also You Can Read This On 📃
11 | - [**medium.com**](https://medium.com/@maitysubham4041)
12 | - [**hashnode**](https://codexam.hashnode.dev)
13 | - [**dev.to**](https://dev.to/codexam)
14 |
15 |
16 | > ### (Check out the website [**Here**](https://codexam.vercel.app/docs/node))
17 |
18 | | **Day** | **Chapter Name** |*Topic*|*Learn About*| **Read on Website** | **Read on GitHub** |
19 | | --- | --- | --- | --- | --- | --- |
20 | | Day 1 | Introduction to Node js and the Course |What is , Why do we use,history, Js vs NodeJS | Chrome's V8 |[**Here**](https://codexam.vercel.app/docs/node/node1) | [**Here**](https://github.com/Subham-Maity/node-js-full-stack-tutorial/tree/main/01.%20Introduction%20to%20Node%20js%20and%20the%20Course) |
21 | | Day 2 | Basic Concepts and Theory of Node js | Client,Server Sides ,NodeJs use JavaScript,What developer Make|Client and Server |[**Here**](https://codexam.vercel.app/docs/node/node2) | [**Here**](https://github.com/Subham-Maity/node-js-full-stack-tutorial/tree/main/02.%20Basic%20Concepts%20and%20Theory%20of%20Node%20js) |
22 | | Day 3 | How to Install and Set Up Node js | Install & Setup | Npm,Node,IDE,|[**Here**](https://codexam.vercel.app/docs/node/node3) | [**Here**](https://github.com/Subham-Maity/node-js-full-stack-tutorial/tree/main/03.%20Install%20and%20Set%20Up%20Node%20js) |
23 | | Day 4 | Writing Your First Node js Script |Hello World,Compile |console.log , node index.js |[**Here**](https://codexam.vercel.app/docs/node/node4) | [**Here**](https://github.com/Subham-Maity/node-js-full-stack-tutorial/tree/main/04.%20Writing%20Your%20First%20Node%20js%20Script) |
24 | | Day 5 | Node js Fundamentals and Features |JsBasic | , filter , module.exports , require ,import,function|[**Here**](https://codexam.vercel.app/docs/node/node5) | [**Here**](https://github.com/Subham-Maity/node-js-full-stack-tutorial/tree/main/05.%20Fundamentals%20and%20Features) |
25 | | Day 6 | Using Core Modules in Node js |What is Core Modules, global modules ,Non-global modules | (**fs-filesystem**) |[**Here**](https://codexam.vercel.app/docs/node/node6) | [**Here**](https://github.com/Subham-Maity/node-js-full-stack-tutorial/tree/main/06.%20Modules) |
26 | | Day 7 | Creating a Basic Server in Node js | Make a Basic Server , arrow function,|(**http ,createServer ,res ,req ,write ,end ,listen**) | [**Here**](https://codexam.vercel.app/docs/node/node7) | [**Here**](https://github.com/Subham-Maity/node-js-full-stack-tutorial/tree/main/07.%20Create%20Basic%20Server) |
27 | | Day 8 | Understanding and Using package.json in Node js |Install Additional Dependencies,package-lock.json ,Uninstall Dependencies,Update Dependencies ,Install Specific Version , | npm | [**Here**](https://codexam.vercel.app/docs/node/node8) | [**Here**](https://github.com/Subham-Maity/node-js-full-stack-tutorial/tree/main/08.%20Package.json) |
28 | | Day 9 | A Small Challenge for You to Test Your Skills | 5 MCQ |Gitignore| [**Here**](https://codexam.vercel.app/docs/node/node9) | [**Here**](https://github.com/Subham-Maity/node-js-full-stack-tutorial/tree/main/09.%20Challenge) |
29 | | Day 10 | What is Nodemon and How to Use it in Node js |How to Install Nodemon, what is, setup in package.json | Why Node.js is an asynchronous language | [**Here**](https://codexam.vercel.app/docs/node/node10) | [**Here**](https://github.com/Subham-Maity/node-js-full-stack-tutorial/tree/main/10.%20Nodemon%20Package) |
30 | | Day 11 |Building a Simple API with Node js |make a server first and add data ,Add More Data ,reformat data.js , Status codes(200,201,204,400,401,403,404,500,503) |(**writeHead & JSON.stringify**) |[**Here**](https://codexam.vercel.app/docs/node/node11) | [**Here**](https://github.com/Subham-Maity/node-js-full-stack-tutorial/tree/main/11.%20Basic%20API%20Create) |
31 | | Day 12 | Taking Input from the Command Line |Running ‘node index.js abc in terminal doesn’t allow input, Create a file with 3 inputs: 2nd is the name and 3rd is the content ,Remove and add the file. |(**process.argv ,writeFileSync ,UnlinkSync ,if-else ,create-file ,remove-file**) |[**Here**](https://codexam.vercel.app/docs/node/node12) | [**Here**](https://github.com/Subham-Maity/node-js-full-stack-tutorial/tree/main/12.%20Taking%20Command%20Line%20Input) |
32 | | Day 13 | Listing Files with the File System Module | Make files in a folder ,need to see the files in the folder ,We don't want to see the files in the array format|(**Path module ,__dirPath ,For Loop,template literals ,fs.readdir ,foreach**) | [**Here**](https://codexam.vercel.app/docs/node/node13) | [**Here**](https://github.com/Subham-Maity/node-js-full-stack-tutorial/tree/main/13.%20Listing%20Files%20with%20the%20File%20System%20Module) |
33 | | Day 14 | Performing CRUD Operations with the File System Module |What is CRUD,Create,Read,Update, Rename,Delete, what is buffer| (**writeFileSync ,readFile ,appendFile ,rename ,unlinkSync ,buffer**) | [**Here**](https://codexam.vercel.app/docs/node/node14) | [**Here**](https://github.com/Subham-Maity/node-js-full-stack-tutorial/tree/main/14.%20CRUD%20Operations) |
34 | | Day 15 | Working with Asynchronous Node js |What is Synchronous & Synchronous with example ,coding example(basic) |setTimeout | [**Here**](https://codexam.vercel.app/docs/node/node15) | [**Here**](https://github.com/Subham-Maity/node-js-full-stack-tutorial/tree/main/15.%20Synchronous%20%26%20Asynchronous) |
35 | | Day 16 | Handling Asynchronous Data in Node js | Promise with detailed Explanation | promise() ,then() | [**Here**](https://codexam.vercel.app/docs/node/node16) | [**Here**](https://github.com/Subham-Maity/node-js-full-stack-tutorial/tree/main/16.%20Handle%20Asynchronous%20Data) |
36 | | Day 17 | How Node js Works Behind the Scenes | Understand the Event Loop, Clearing The Confusion , Explain with Example and step by step process |Even Loop,Node APIs,callback queue,call stack,LIFO,FIFO, Dequeue, Enqueue | [**Here**](https://codexam.vercel.app/docs/node/node17) | [**Here**](https://github.com/Subham-Maity/node-js-full-stack-tutorial/tree/main/17.%20Node%20js%20Works%20with%20Event%20Loop) |
37 | | Day 18 | Introduction to Express js Framework | What is Express , Install, Basic Use | get, post, put, delete ,(req, res),res.send , listen , Port | [**Here**](https://codexam.vercel.app/docs/node/node18) | [**Here**](https://github.com/Subham-Maity/node-js-full-stack-tutorial/tree/main/18.%20Introduction%20to%20Express) |
38 | | Day 19 | Routing with Express.js | Diagram , Server & Client in Detail , how each HTTP method works , HTTP request and response process , Request and Response , request object (req) details , response object (res) details , use req and res , Example of using req and res | req,res,req.query,get | [**Here**](https://codexam.vercel.app/docs/node/node19) | [**Here**](https://github.com/Subham-Maity/node-js-full-stack-tutorial/tree/main/19.%20Routing%20with%20Express.js(req%20%2C%20res)) |
39 | | Day 20 | Rendering HTML Pages with Node js | Html render, Redirect, Json Data , Input Print | HTML tag(h1,input,button,a href) , json data , req.query , value place | [**Here**](https://codexam.vercel.app/docs/node/node20) | [**Here**](https://github.com/Subham-Maity/node-js-full-stack-tutorial/tree/main/20.%20Html%20Render) |
40 | | Day 21 | Creating HTML Pages with Node js | Html & CSS make + Render on Browser | html, css , path.join , __dirname , express.static | [**Here**](https://codexam.vercel.app/docs/node/node21) | [**Here**](https://github.com/Subham-Maity/node-js-full-stack-tutorial/tree/main/22.%20Make%20HTML%20Page) |
41 | | Day 22 | Removing File Extensions from URLs |Remove extension from URL + 404(default) | sendFle,different endpoint,``*``(default 404) | [**Here**](https://codexam.vercel.app/docs/node/node22) | [**Here**](https://github.com/Subham-Maity/node-js-full-stack-tutorial/tree/main/22.%20Remove%20extension%20from%20URL) |
42 | | Day 23 | Creating Dynamic Pages with EJS | | | | |
43 | | Day 24 | Dynamic Page in Node.js | | | | |
44 | | Day 25 | Middleware in Node.js | | | | |
45 | | Day 26 | Using Route-Level Middleware in Express js | | | | |
46 | | Day 27 | Installing MongoDB for Node js | | | | |
47 | | Day 28 | Basics of MongoDB Database | | | | |
48 | | Day 29 | Performing CRUD Operations with MongoDB | | | | |
49 | | Day 30 | Connecting MongoDB with Node js | | | | |
50 | | Day 31 | Reading Data from MongoDB to Node.js | | | | |
51 | | Day 32 | Inserting Data from MongoDB to Node.js | | | | |
52 | | Day 33 | Updating Data from MongoDB to Node.js | | | | |
53 | | Day 34 | Deleting Data from MongoDB to Node.js | | | | |
54 | | Day 35 | GET API with MongoDB and Node.js | | | | |
55 | | Day 36 | POST API Method with Node.js and MongoDB | | | | |
56 | | Day 37 | Building PUT APIs with MongoDB and Node js | | | | |
57 | | Day 38 | Building DELETE APIs with MongoDB and Node js | | | | |
58 | | Day 39 | Introduction to Mongoose Library | | | | |
59 | | Day 40 | Performing CRUD Operations with Mongoose | | | | |
60 | | Day 41 | Building POST APIs with Mongoose | | | | |
61 | | Day 42 | Building GET, DELETE and PUT APIs with Mongoose | | | | |
62 | | Day 43 | Building Search APIs with Mongoose | | | | |
63 | | Day 44 | Using OS Module in Node js | | | | |
64 | | Day 45 | CRUD Operations in Node.js | | | | |
65 | | Day 46 | Using Events and Event Emitter in Node js | | | | |
66 | | Day 47 | Using REPL in Node js | | | | |
67 | | Day 48 | Connecting Node js with MySQL Database | | | | |
68 | | Day 49 | Building POST APIs with Node js and MySQL | | | | |
69 | | Day 50 | Building PUT APIs with Node js and MySQL | | | | |
70 | | Day 51 | Building DELETE APIs with Node js and MySQL | | | | |
71 | | Day 52 | Comparing Node js and PHP | | | | |
72 |
73 | ## Prerequisites 📋
74 |
75 | Before diving into Node.js, you should have a basic understanding of JavaScript and web development concepts.
76 |
77 | ## Projects you will build 🛠️
78 |
79 | Throughout this content list, you will learn how to build various projects with Node.js, including building servers, creating APIs, connecting to databases, and more.
80 |
81 | ## What you will learn 📚
82 |
83 | By the end of this content list, you will have a strong understanding of Node.js and be able to build your own applications using this technology.
84 |
85 |
86 | ## How to start 🚀
87 |
88 | To start this tutorial:
89 |
90 | 1. Clone this repository or download it as a zip file.
91 |
92 | 2. Open each project folder in your code editor.
93 |
94 | 3. Follow the instructions in each project's README file.
95 |
96 | Once you have Node.js installed, clone this repository and navigate to the project directory in your terminal. From there, you can follow along with the course by running the examples in each section.
97 |
98 | ## Contributing 💖
99 |
100 | If you want to contribute to this tutorial:
101 |
102 | 1. Fork this repository or create a new branch.
103 |
104 | 2. Make your changes or additions.
105 |
106 | 3. Create a pull request with a clear description of your changes.
107 |
108 | We appreciate any feedback or suggestions that can help us improve this tutorial. Thank you! 😊
109 |
110 | ## License 📄
111 |
112 | This tutorial is licensed under the MIT License - see [LICENSE](LICENSE) file for details.
--------------------------------------------------------------------------------
/11. Basic API Create/README.md:
--------------------------------------------------------------------------------
1 |
2 | ## ⭐ Make a Server First
3 |
4 |
5 |