Nodejs (Harry)

1/1/1970

Nodejs (Harry)

Node Js Tutorial in Hindi šŸ”„šŸ”„

What is NodeJs?

         |                    |
	     |                    |
Client ---------Request--------->
       <--------Response--------- Server
         |                     |   
         |                     |

Note:

Setup NodeJS

  1. Download Nodejs nodejs.org
  2. Install Nodejs
  3. Check Version by typing node --version in any terminal
  4. Now You can use Node.js Terminal to Run Javascript

Npm


Let Start

project/
└──  index.js
node index
npm init
project/
ā”œā”€ā”€ index.js
└── package.json

package.json

npm install <package_name> --save #npm i <package_name> --save
npm install <package_name> --save-dev
npm uninstall <package_name>
project/
ā”œā”€ā”€ node_modules/
ā”œā”€ā”€ package.json
└── package-lock.json

node_modules/

package-lock.json


Basic Nodejs

Create A NodeJS File index.js

// Index.js
console.log("Hello world")

Create Another Node file gaurav.js

// gaurav.js
gaurav = {
	name: "gaurav meena".
	favNum: 3,
	developer: true
}

**Import gaurav.js in index.js **

// Index.js
const grv = require("./gaurav")
...

**Export gaurav from gaurav.js **

...
module.exports = gaurav

Module Wrapper Function ⭐

Nodejs Wrap modules in this format

function(exports, require, module, __filename, __dirname)

Note:


Import and Export

Common JS (`.cjs/)

// ExportCommon.js
function simple(){
	console.log("Simple")
}
 
module.exports = simple
// ImportCommon.js
const simple = require("./ExportCommon")
simple()
 

Note: You can't use require() in mjs module

ECMA Script (ES6) (.mjs)

// ExportES6.mjs
 
// Define and Export Default Function
export default function simple(){
	console.log("simple default")
}
 
// Define and Export Named function
export function simple1(){
	console.log("Simpl 1")
}
 
// Define Named function
function simple2(){
	console.log("Simple 2")
}
 
// Export Named function
export simple2();
 
module.exports = simple
// ImportES6.mjs
import defsimple {simple1, simple2} from "./ExportES6.mjs"
 
simple2()

Note:

Import Named Export as Alias Name

import {funcName as aliasFunc Name} from (.'/Module.js')

Import Everything from a module

import * as mymod from "./ExportES6.mjs"
 
console.log(mymod.simple())

Node.js Importing Rules:

  1. Extensions You Can Skip: - .js, .json, .node
  2. When to Include Extensions:
    • Custom files (e.g., .txt, .mjs)
    • Using import (ESM modules)
  3. Resolution Order:
    • Exact match → Directory index.js → Core modules.
  4. In JavaScript, there is no functional difference between " (double quotes) and ' (single quotes). Both can be used interchangeably to represent string literals.

Inbuilt NodeJS Modules

Node.js Documentation -> Nodejs.org/docs Amazing Website to Learn Node.jsNodejs.dev

Operating System Module

const os = require('os');
// Return free memory in your pc 
os.freemem()
 
// Return users Home directory  `C:/Users/Gaurav`
os.homedir()  
 
//  Return hostname of your computer `DESKTOP-UBQMKH7`
os.hostname
 
// Return platform of your OS `win32`
os.platform()
 
// Return releas version of your os `10.0.19042`
os.release()
 
// Return type of your os `Windows_NT`
os.type()

Path Module

const path = require('path');
// Return basename of path i.e 'myfile.html'
path.basename('C:\\temp\\myfile.html')
 
// Return directory name of path i.e 'C:\temp'
path.dirname('C:\\temp\\myfile.html')
 
// Return extension of path i.e `.js`
path.extname(__filename)
 

URL Module

import url from 'url';
 
const myURL = new URL('https://example.org:8000')
myURL.pathname = '/a/b/c';
myURL.has = '#fgh'
 
console.log(myURL.href) // 'https://exampte.org:8000/a/b/c?d=e#fgh'
 
console.log(myURL) // URL {...} 
URL {
	href: 'https://exampte.org:8000/a/b/c?d=e#fgh',
	origin : 'https://example.org:'
	protocol : 'https:',
	username : '',
	password : '',
	host : 'example.org:8000'
	hostname: 'example.org',
	port : '8000',
	pathname : '/a/b/c '
	search: '?d=e'
	searchParams: URLSearchParams { 'd' => 'e'},
	hash: '#fgh'
}

File System Module

const fs = require('fs');
// fs.readFile(path, options, callback)
fs.readFile('file.txt', 'utf8', (err, data) => {
    console.log(err, data); // null indicate no error
});
console.log("Finished reading file");
- OUTPUT
Finished reading file
null (file.txt content)
fs.readFileSync('file.txt')
console.log(a.toString())
 
console.log("Finished reading file");
- OUTPUT
(file.txt content)
Finished reading file
fs.writeFile('file2txt', "This is a data", ()=>{
	console.log("Written to the file")
})
 
console.log("Finished reading file")
- OUTPUT
Finished reading file
Written to the file
fs.writeFileSync('file2txt', "This is a data")
 
console.log("Finished reading file")
- OUTPUT
Finished reading file
Written to the file

Non-blocking I/O in Node.js:


Event Emitter ⭐

NodeJS Works on event driven architecture i.e. You can fire event from anywhere, and If a event is fired you can listen for it

When to use EventEmitter:

// Import EventEmitter from 'events' module 
const EventEmitter = require('events');
 
// Creating custom class inherits from built-in EventEmitter class.
class MyEmitter extends EventEmitter {}
 
// Creating an instance of the 'MyEmitter' 
const myEmitter = new MyEmitter(); 
 
// Setting up an event listener for the 'WaterFull' event.
myEmitter.on('WaterFull', () => {
    
    // logged immediately when 'WaterFull' event is emitted.
    console.log('Please turn off the motor!');
    
    setTimeout(() => {
        
        // This message is logged after a 3-second delay.
        console.log('Please turn off the motor!');
        
    }, 3000); 
});
// triggering the 'WaterFull' event, which calls the listener function.
myEmitter.emit('WaterFull'); 

HTTP ⭐

const http = require('http')
const server = http.createServer((req, res)=>{
	res.statusCode = 200;
	res.setHeader('Content-Type', 'text/html')
	res.end('<h> Hello </h> <p> hello world! </p>');
	// console.log(req)
})
server.listen(8000, ()=>{
	console.log('server is running on port 8000')
});

Request Object

HTTP Status Codes

PORT from Environment Variable

const port = process.env.PORT || 2000; // If PORT not set i.e. undefined, then port = 2000
server.listen(port, ()=>{
	console.log(`server is running on port ${port}`)
});
server.listen(port, ()=>{
	console.log(`server is running on port http://localhost:${port}`)
});
 
// If Port is `8000`
// it will console `http://localhost:8000`
const server = http.createServer((req, res)=>{
	...	
	// Respone when result Url is '/'
	if(req.url=='/'){
		res.end('<h1> hello </h1> <p> Hello this is me </p>')
	}
	// Response when Request url is '/about'
	else if(req.url == '/about'){
		res.end('<h1> hello </h1> <p> Hello this is me </p>')
	}
})
const server = http.createServer((req, res)=>{
...
// Move and Set Corresponding status code in each Route block
 
	if(req.url=='/'){
		res.statusCode = 200; // OK
		res.end('<h1> hello </h1> <p> Hello this is me </p>')
	}
	else if(req.url == '/about'){
		res.statusCode = 200; // OK
		res.end('<h1> hello </h1> <p> Hello this is me </p>')
	}
	// If requested some other URL
	else{ 
		res.statusCode = 404; // Not Found
		res.end('<h1>Not Found</h1> <p>This page was not found on this server</p>')
	}
})
// Import FS
const fs = require('fs')
 
const server = http.createServer((req, res)=>{
	...
	// read HTML File
	const data = fs.readFileSync('index.html')
	// response file
	res.end(data.toString());
	...
})

Note:


Nodemon

nodemon is a tool that automatically restarts your Node.js application when it detects file changes.

Why Need Nodemon?

npm install nodemon
# or 
npm install -g nodemon # install it globally

Express

express is a Fast, unopinionated, minimalist web framework for Node.js

npm install express
// Import Express
const express = require('express')
const app = express()
const port = 3000
 
// Route Request at `/` URL
app.get('/', (req, res)=>{
	res.send('Hello World!')
})
 
// Route Request at `/` URL
app.get('/about', (req, res)=>{
	res.send('This is About Page')
}) 
 
app.listen(8000, ()=>{
	console.log('Express app listening at port 8000')
})

Done Tutorial āœ…


Deploy a Node.js Application on DigitalOcean (Optional)

Step 1: Set Up a DigitalOcean Droplet

  1. Log in to DigitalOcean.
  2. Create a Droplet (choose Ubuntu as the operating system).
  3. Choose a plan (basic plan is sufficient for small apps).
  4. Add your SSH key (for secure access) or use a root password.
  5. Launch the Droplet and note down the IP address.

Step 2: Access the Droplet

  1. Open a terminal and connect via SSH:

    ssh root@your-droplet-ip
  2. Update and upgrade packages:

    sudo apt update && sudo apt upgrade -y

Step 3: Install Node.js and npm

  1. Install Node.js and npm:

    sudo apt install nodejs npm -y
  2. Verify installation:

    node -v
    npm -v

Step 4: Upload Node.js Application

  1. Clone your Node.js project from GitHub:

    git clone https://github.com/your-repo.git
  2. Move to the project directory:

    cd your-repo
  3. Install project dependencies:

    npm install
  4. Start the application:

    node app.js

    (Ensure your app listens on port 3000 or any desired port.)

Step 5: Set Up PM2 (Optional for Process Management)

  1. Install PM2 globally:

    npm install -g pm2
  2. Start your Node.js app:

    pm2 start app.js
  3. Set PM2 to auto-start on reboot:

    pm2 startup
    pm2 save

Step 6: Configure Nginx as a Reverse Proxy

  1. Install Nginx:

    sudo apt install nginx -y
  2. Create an Nginx configuration file:

    sudo vi /etc/nginx/sites-available/nodeApp
  3. Add the following content:

    server {
        server_name your-droplet-ip;
     
        location / {
            proxy_pass http://localhost:3000;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            proxy_set_header Host $host;
            proxy_cache_bypass $http_upgrade;
        }
    }
  4. Enable the configuration:

    sudo ln -s /etc/nginx/sites-available/nodeApp /etc/nginx/sites-enabled
  5. Test and reload Nginx:

    sudo nginx -t
    sudo systemctl restart nginx

Step 7: Allow Traffic Through Firewall

  1. Allow HTTP and HTTPS traffic:
    sudo ufw allow 'Nginx Full'
    sudo ufw enable

Step 8: Access Your Application

Visit http://your-droplet-ip in a browser to see your Node.js app running.

āœ… Done! Your Node.js app is now live on DigitalOcean.