1/1/1970
What is NodeJs?
| |
| |
Client ---------Request--------->
<--------Response--------- Server
| |
| |
NodeJS, PHP, Django, Flask, RailsNote:
Setup NodeJS
node --version in any terminalNode.js Terminal to Run JavascriptNpm
npm by npm --versionindex.js in a Directoryproject/
āāā index.js
node indexnpm initproject/
āāā index.js
āāā package.json
package.json
After file package.json will be created and will store all information related to project.
dependencies -> Packages used In both Development and Production. ex express
devDependencies -> Package used only during Development ex nodemon
Installing package
npm install <package_name> --save #npm i <package_name> --save--save will store the package related information in package.json. (optional in npm 5+)
Install Package as Dev dependency
npm install <package_name> --save-devnpm uninstall <package_name>project/
āāā node_modules/
āāā package.json
āāā package-lock.json
node_modules/
node_modules/ directory will be created, and will store all the packages.npm installpackage-lock.json
pakcage-lock.json Contains All these Dependencies of Dependencies in package.jsonCreate 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 = gauravNodejs Wrap modules in this format
function(exports, require, module, __filename, __dirname)Note:
--dirname return the path of current directory of module or file--filename return the path of current directory of module/filemodule.exports = functionName// ExportCommon.js
function simple(){
console.log("Simple")
}
module.exports = simpleconst aliasFunctionName = require("./ModuleName)// ImportCommon.js
const simple = require("./ExportCommon")
simple()
Note: You can't use require() in mjs module
.mjs)export functionName// 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 = simpleimport defaultExport {Named Export} from "./ModuleName"// ImportES6.mjs
import defsimple {simple1, simple2} from "./ExportES6.mjs"
simple2()Note:
.js , set type ="module" in `package.json{} and Named Function with {}Import Named Export as Alias Name
{} unlike Named Function . To import named function with alias name useimport {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:
.js, .json, .node.txt, .mjs)import (ESM modules)index.js ā Core modules." (double quotes) and ' (single quotes). Both can be used interchangeably to represent string literals.Node.js Documentation -> Nodejs.org/docs Amazing Website to Learn Node.jsNodejs.dev
os moduleconst os = require('os');os Functions// 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 moduleconst path = require('path');path Functions// 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)
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'
}fs moduleconst fs = require('fs');file.txt) Asynchronously// 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)
NodeJS works on Non-blocking I/O. it does not wait for the file to be read it immediately moves to the next operation (console.log("Finished reading file");).
fs.readFile() starts reading the file asynchronously -> "Finished reading file" is printed immediately. -> Once the file is fully read, the callback is executed, printing the file contents.
Read File in Synchronous manner
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:
libuv is a C library that provides asynchronous I/O and event-driven capabilities for Node.js. It is the core engine responsible for handling non-blocking operations in Node.js.fs.readFile() is called, it delegates the file reading task to the libuv thread pool.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:
When you want to trigger multiple actions based on specific events.
Ideal for asynchronous and loosely-coupled code where different parts of the application respond to the same event.
Useful for real-time systems like handling user input, I/O operations, or API responses.
Create an Event Object
// 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'); const http = require('http')createServer() ā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
console.log(req) inside server function. or through Network tab in Browser (F12)req objectsHTTP Status Codes
PORT from Environment Variable
const port = process.env.PORT || 2000; // If PORT not set i.e. undefined, then port = 2000server.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:
res.end() sends the response to the client and ends the connection.
If no URL is given, the server treats it as the root route ('/').
Sometimes, it becomes too time-consuming to write route requests using the above http method.
To write HTTP web requests in a better, more convenient, and efficient way, we use Express.
nodemon is a tool that automatically restarts your Node.js application when it detects file changes.
Why Need Nodemon?
When you write error or bug code, the Node.js server may crash.
It monitors your code for changes and restarts the server automatically after crashes or updates, saving time during development.
Install nodemon
npm install nodemon
# or
npm install -g nodemon # install it globallyexpress is a Fast, unopinionated, minimalist web framework for Node.js
expressnpm install expressserver.js// 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 ā
Step 1: Set Up a DigitalOcean Droplet
Step 2: Access the Droplet
Open a terminal and connect via SSH:
ssh root@your-droplet-ipUpdate and upgrade packages:
sudo apt update && sudo apt upgrade -yStep 3: Install Node.js and npm
Install Node.js and npm:
sudo apt install nodejs npm -yVerify installation:
node -v
npm -vStep 4: Upload Node.js Application
Clone your Node.js project from GitHub:
git clone https://github.com/your-repo.gitMove to the project directory:
cd your-repoInstall project dependencies:
npm installStart 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)
Install PM2 globally:
npm install -g pm2Start your Node.js app:
pm2 start app.jsSet PM2 to auto-start on reboot:
pm2 startup
pm2 saveStep 6: Configure Nginx as a Reverse Proxy
Install Nginx:
sudo apt install nginx -yCreate an Nginx configuration file:
sudo vi /etc/nginx/sites-available/nodeAppAdd 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;
}
}Enable the configuration:
sudo ln -s /etc/nginx/sites-available/nodeApp /etc/nginx/sites-enabledTest and reload Nginx:
sudo nginx -t
sudo systemctl restart nginxStep 7: Allow Traffic Through Firewall
sudo ufw allow 'Nginx Full'
sudo ufw enableStep 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.