❖Introduction
- Node js written by ryan dahl in 2009
- Node.js is a cross-platform,open-source server environment that
can run on Windows, Linux, Unix, macOS, and many more.
- Node.js is a back-end JavaScript runtime environment, runs on the
V8 JavaScript Engine
- Node js is a server side scripting language
- javascript write on browser to understand v8 engine
- Node.js is the greatest tool for building real-time web applications
- It provides cross-platform applications which run easily on any web.
- According to the Node.js Survey of users, 43% of Node.js
programmers claim to use Node.js for enterprise apps
❖Why node js
- Node. js is that allows developers to build fast and scalable
network applications
- Node js help to create a real time application like a video
conferencing
- Node js is no sql database
- Node js is fast to compare other language
- Node js is a query less language
❖ Concepts Of No Sql
❖Node Modules
- Node.js has a set of built-in modules which can be used without
any further installation.
- We can install some custom modules from the NPM as per the need
of the application
- We can also create modules of our own and use them by importing
it in our apps.
- The modules in node.js work independently without impacting the
existence of any other functions.
❖Npm (Node Package Manager)
- These are the libraries which are built by the awesome community
which will solve almost all the generic problems related to the
Node.js
- Npm has packages which are used in our apps to make the
development process faster and more efficient.
❖Node js installation
- Step 1 : search in google download node js
- Step 2 : download and install
- Step 3 : go to c drive👉 program files 👉 node js👉 copy url
- Step 4 : open env
- Step 5 : click new
- Step 6 : fill the data and click ok
- Step 7 : restart your device
- Step 8 : open cmd
- Step 9 : write node –v
- Step 10 : Display your node version to success your node
installation
Wap to print hello
- Step 1 : create a index.js file
console.log(‘hello skywin’);
- Step 2 : run this file to node index.js
❖File system(fs)
- The node js file system module allows you to work with the file
system on your computer
- To handle file operations like creating, reading, deleting, etc.
- Node.js provides an inbuilt module called FS (File System).
- To include the file system module use the require() method
- All file system operations can have synchronous and asynchronous
forms depending upon user requirements
- Common use for the File System module:
- create file
- read file
- delete file
- write file
Syntax :
fs.writeFile(‘file name’ , ‘write your content’ , callback
function(err)=>{
console.log(‘create file’)
})
Create file :
- Step 1 : create file index.js => require path
const fs = require(‘fs’)
fs.writeFile(‘read.txt’ , ‘hello skywin’ , (err) =>{
console.log(‘file is created’)});
Read file:
Syntax :
fs.readFile(‘file name’ , callback function(err ,
data)=> {
console.log(read file’ , data.toString())
})
Ex:
fs.readFile(‘read.txt’ , (err , data)=>{
console.log(data.toString())});
Add content :
Syntax :
Fs.appendfile(‘file name’ , ‘write your content’ , callback
function(err)=>{
console.log(write file’)
})
Ex :
fs.appendFile(‘read.txt’ , ‘how are you’ , (err) => {
Console.log(‘write content’)});
Delete your file
Syntax :
fs.unlink(‘file name’ , callback function(err)=>{
console.log(delete file’)
})
Ex:
fs.unlink(‘read.txt’ , (err)=>{
console.log(‘deleted file’)
});
❖Create server
- Node.js has a built-in module called HTTP, which allows Node.js to
transfer data over the HyperText Transfer Protocol (HTTP).
- To include the HTTP module, use the require() method:
- The HTTP module can create an HTTP server that listens to server
ports and gives a response back to the client.
- Use the createServer() method to create an HTTP server:
- The function passed into the http.createServer() method
Step 1 : npm I
Step 2 : npm init –y
Step 3 : search npm http-server on google
Step 4 : install
Step 5 : create new file index.js
Step 6 : require http
Step 7 : create server
Step 8 : assign a port
Step 9 : node index.js for run your project
Example :
var http = require('http’)
http.createServer(function(req , res){
res.write(‘hello skywin’ );
res.end()
}).listen(3030)
❖Create a routing
- Routing defines the way in which the client requests are handled by
the application endpoints
- There are two ways to implement routing in node.js which are
listed below:
- By Using Framework
- Without Using Framework
- Using Framework: Node has many frameworks to help you to get
your server up and running. The most popular is Express.js.
- Routing without Framework: Using the frameworks is good to save
time, but sometimes this may not suit the situation. So, a developer
may need to build a custom Routing
- Step 1 : npm init -y
- Step 2 : search on google npm express
- Step 3 : install express (npm i express)
- Step 4 : create a file index.js
- Step 5 : require express
- Step 6 : create a routing
Example :
const express = require('express')
const app = express()
app.get('/' , function(req , res){
res.send('hello world')
})
app.get('/blog' , function(req , res){
res.send('blog world')
})
app.listen(3030)
❖Form
How to get data html to node js ?
Express js is a node js framework.
It’s the most popular framework as of now
- Step 1 ; npm init –y
- Step 2 : npm I express
- Step 3 : npm body-parser
- Step 4 : npm I path
- Step 5 create new file index.js
- Step 6 : create new file form.html
Index.js file
var express = require('express')
var app = express();
var bodyParser = require('body-parser’);
var path = require('path')
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.get('/',function(req,res) {
res.sendFile(path.join(__dirname+'/form.html'));
});
app.post('/' , function(req,res){
var name = req.body.name
var email = req.body.email
console.log(name + email);
res.send('success')
})
app.listen(3030)
❖Mongodb download & installation
- MongoDB is a source-available cross-platform document-oriented
database program.
- Classified as a NoSQL database program, MongoDB uses JSON-like
documents with optional schemas
- that is designed to store, manage, and retrieve data in a flexible and
scalable manner
- Unlike traditional relational databases, which use tables and rows,
MongoDB stores data in JSON-like documents with dynamic
schemas, known as BSON (Binary JSON).
- This flexibility allows developers to work with data that can vary in
structure and size without needing to modify the database schema.
- Mongodb is an free and open source database
- Mongodb is query less or non structure database
- Step 1 : mongodb download for search on google
(https://www.mongodb.com/try/download/community)
- Step 2 : download and install
❖ Synchronous
- Working on one task at a time and starting another task after
finishing it is called Synchronous Language
- Synchronous, sometimes referred to as “sync”
- One thing to note about JavaScript is it is synchronous by default,
but there are APIs given in the environment (browser, Node.js, etc.)
that could make it asynchronous
❖ Asynchronous
- Working on one task at a time and receiving another request at the
same time is called asynchronous language.
- Node js is asynchronous language
- asynchronous, also known as “async,” are two types of
programming models.
- If you want to use await, so function has to be asynchronous
- The function will not be called further until one data is received i.e.
the next data will not be printed.
- When a function is marked as async, it can perform asynchronous
operations, and you can use the await keyword to pause the
execution of that function until an asynchronous operation
completes.
Ex :
setTimeout(()=>{
console.log('function one called');
},5000)
setTimeout(()=>{
console.log('function two called');
},2000)
setTimeout(()=>{
console.log('function three called');
},3000)
Insert data in database
Step 1 : npm I
Step 2 : npm init –y
Step 3 : npm i mongoose
Step 4 : require mongoose and connect mongo db
Schema : a mongoose schema defines the structure of document like a
default values validators etc
Step 5 : make a schema and define a model
Step 6 : use function .save and insert data
Make a Schema :
const Schema = mongoose.Schema;
var my = new Schema({
name:({
type:String
}),
email:({
type:String
})
})
const MyModel = mongoose.model('table', my);
Insert data into mongodb
const model = new MyModel({
name: "skywin",
email: "skywin@gmail.com"
})
model.save()
console.log('data is inserted');
Getdata into mongodb
var get = async ()=>{
var data = await MyModel.find();
console.log(data);
get();
Edit Data into mongodb
var edit = async (id) => {
console.log(id);
var obj = {
name: 'ravi',
email: 'ravibadrukhiya@gmail.com'
var data = await MyModel.findByIdAndUpdate(id , obj)
console.log('data is updated');
edit('6458f3eafb39cb65685b68d7')
Delete data into mongodb
var del = async (id) =>{
var data = await MyModel.findByIdAndDelete(id)
del('6458f60a5416d7de09c600d1')
❖Express js
- Express.js is a web framework for Node.js. It is fast, robust and
asynchronous in nature.
- You can assume express as a layer built on the top of the Node.js
that helps manage a server and routes
- It can be used to design single-page, multi-page and web
applications.
- It defines a routing table which is used to perform different actions
based on HTTP method and URL
- It allows to setup middlewares to respond to HTTP Requests.
- It allows dynamically render HTML Pages based on passing
arguments to templates.
❖Why use express js
- Ultra fast i/o
- Asynchronous and single threaded
- Single threaded processes contain the execution of instructions in a
single sequence. In other words, one command is processes at a
time.
- MVC like structure
- Robust API makes routing easy
- ExpressJS is designed to be fast and efficient, with a lightweight
architecture that allows it to handle large amounts of traffic with
ease.
- ExpressJS can be easily integrated with other popular technologies
and frameworks, such as databases, templating engines, and more
- This makes it simple to build complex and feature-rich web
applications
❖Template Engine
- Html content add dynamic data for use template engine
- Template engine is provide all packages and folder structure
- Template engines provide many templates like a (pug , haml.js , ejs ,
hbs , combyne.js , jade etc…)
Step 1 : npx express-generator –e
Step 2 : npm I nodemon
Step 3 : npm I mongoose => mongoose require and mongodb
connection in www folder
Step 4 : create models folder and create new file and make a schema
Step 5 : create a crud using a postman
❖Schema Types & Validation
Types :
- String
- Number
- Date
- ObjectId
- Array
String Ex :
name:({
type:String
})
Number Ex :
products:({
type:Number
})
Date Ex :
date:({
type:Date,
default:Date.now
})
ObjectId ex :
subid:({
sub:mongoose.Types.ObjectId
})
Array Ex :
multiple:[Schema.Types.Mixed]
❖Validations :
- Schema validation lets you create validation rules for your fields,
such as allowed data types and value ranges
- Validation is defined in the schema types.
- Validation always runs as the first hook
- Mongoose has several built-in validators.
- All SchemaTypes have the built-in required validator.
- Numbers have min and max validators.
- Strings have enum , match , minlength , and maxlength validators.
- Schema validation is an important step in building a robust and
secure Node. js applications
- It involves validating the data that is passed to your application
against a predefined schema, which helps to ensure that the data is
of the correct type, format, and structure.
There are two types of validator
1) Built in validation
2) Custom validation
Step 1: npm I schema
Step 2 :install and require
Step 3 : insert valid data in mongodb
Ex :
name:({
type:String,
required:[true , 'please insert name'],
}),
email:({
type:String,
unique:true
}),
age:({
type:Number
}),
createdat:({
type:Date,
default:Date.now
}),
password:({
type:String,
minlength:[8 , 'enter password must be 8 character up'],
maxlength:16
}),
option:({
type:String,
enum:{
values:['coffee' , 'tea'],
message:'your value is not supported please be choose coffee or
tea'
}),
❖ Joi Validation
- The most powerful schema description language and data
validator for JavaScript.
- Preferable task
- a required string
- must contain only alphanumeric characters
- at least 3 characters long but no more than 30
- an optional string
- must satisfy the custom regex pattern
- TLD must be .com or .net
- a valid email address string
- an integer between 1900 and 2013
Ex :
var registerobj = Joi.object({
name:Joi.string().min(3).max(11).required(),
email:Joi.string().email().required(),
password:Joi.string().pattern(new RegExp('^[a-zA-Z0-9]{3,30}$')),
repeat_password: Joi.ref('password'),
})
router.post('/adddata', validator.body(registerobj), async function (req,
res, next) {
try {
res.status(401).json({
status: 'success'
})
catch (err) {
res.status(401).json({
status: 'alert',
err
})
}
});
❖Restful api
- Restful api stands for representational state transfer application
programming interface
- In today's world, APIs (Application Programming Interfaces) play a
crucial role in connecting different software systems and allowing
them to communicate with each other.
- RESTful API is an interface that two computer systems use to
exchange information securely over the internet. Most business
applications have to communicate with other internal and
third-party applications to perform various tasks.
- If you're working with software systems or just want to understand
how different websites and apps work together, it's important to
understand the basics of REST APIs.
- Overall, a REST API is a crucial tool for allowing different software
systems to communicate with each other and exchange information
seamlessly.
❖Comparison Query Operator
- $eq : Matches values that are equal to a specified value.
Syntax :
{ <field>: { $eq: <value> } }
inventory.find( { "item.name": { $eq: "ab" } } )
inventory.find( { "item.name": "ab" } )
Ex :
var data = await user.find({city:{$eq:'surat'}})
var data = await user.find({city:'surat'})
- $gt : Matches values that are greater than a specified value.
Syntax :
{ field: { $gt: value } }
inventory.find( { quantity: { $gt: 20 } } )
Ex :
var data = await user.find({products:{$gt:20}})
- $gte : Matches values that are greater than or equal a specified
value.
Syntax :
{ field: { $gte: value } }
inventory.find( { quantity: { $gte: 20 } } )
Ex : var data = await user.find({products:{$gte:20}})
- $lt : Matches values that are less than a specified value.
Syntax :
{ field: { $lt: value } }
inventory.find( { quantity: { $lt: 20 } } )
Ex :
var data = await user.find({products:{$gt:20}})
- $lte : Matches values that are less than or equal a specified value.
Syntax :
{ field: { $lte: value } }
inventory.find( { quantity: { $lte: 20 } } )
Ex :
var data = await user.find({products:{$lte:20}})
- $ne : Matches values that are not equal a specified value.
Syntax :
{ field: { $ne: value } }
inventory.find( { quantity: { $ne: 20 } } )
Ex :
var data = await user.find({products:{$ne:20}})
- $in : Matches any of the values specified in an array.
Syntax :
{ field: { $in: [<value1>, <value2>, ... <valueN> ] } }
inventory.find( { quantity: { $in: [ 5, 15 ] } } )
Ex :
var data = await user.find({products:{$in:[ 20, 18 ]}})
- $nin : Matches none of the values specified in an array.
Syntax :
{ field: { $nin: [<value1>, <value2>, ... <valueN> ] } }
inventory.find( { quantity: { $nin: [ 5, 15 ] } }, { _id: 0 } )
Ex :
var data = await user.find({products:{$nin:[ 20, 18 ]}})
❖Logical Operator
- $and : Matches all values must be .
Ex :
var data=await user.find({$and:[{city:'gandhinagar'},{products:{$gt:20}}]})
- $or : At Least one condition must be true.
Ex :
var data = await user.find({$or:[{'price':{$gt:2000}},{'name':'abc'}]})
- $not : It is used to invert the effect of the query expressions and
return documents that does not match the query expression.
Ex :
var data = await user.find({'price':{$not:{$eq:100}}})
❖Cursor Methods
- sort : The cursor.sort() method is used to return results ordered
according to a sort specification. Specify in the sort parameter the
field or fields to sort by and a value of 1 or -1 to specify an
ascending or descending sort respectively.
Ex :
var data = await user.find({price:{$gt:250}}).sort({price:1});
- Count : The cursor.count() method is used to return the total
number of documents in a cursor. Append the count() method to a
find() query to return the number of matching documents.
Ex :
var data = await user.find({price:{$gt:250}}).count();
- Limit : Use the limit() method on a cursor to specify the maximum
number of documents the cursor will return. limit()
Ex :
var data = await user.find({price:{$gt:250}}).limit(2);
- Skip : The cursor. skip() method is used to return a cursor that
begins returning results only after passing or skipping a number of
documents.
Ex :
var data = await user.find({price:{$gt:250}}).limit(5).skip(2);
- Projection : Use a projection to control which fields appear in the
documents returned by read operations.
- Many requests only require certain fields, so projections can help
you limit unnecessary network bandwidth usage.
Ex :
var data = await user.find({},{name:1 })
var data = await user.find({},{products:1 , _id:0})
❖Aggregation
- Aggregation is the process of performing transformations on
documents and combining them to produce computed results.
$match :
Ex :
var data = await user.aggregate([
{$match:{'products':12 }}
])
var data = await user.aggregate([
{$match:{'name':"abc6"}},
{$sort:{'products':1}}
])
$Project :
var data = await user.aggregate([
{$project:{'name':1, _id:0 }}
])
var data = await user.aggregate([
{$match:{'products':{$lt:98}}},
{$project:{'name':1, _id:0 }}
])
var data = await user.aggregate([
{$match:{'products':{$lt:98}}},
{$project:{'name':1, _id:0 , 'products':1}},
{$sort:{products:-1}}
])
$lookup :
- The $lookup operator is an aggregation operator or an aggregation
stage, which is used to join a document from one collection to a
document of another collection of the same database based on some
queries. Both the collections should belong to the same databases.
- This aggregation stage performs a left outer join to a collection in the
same database.
There are four required fields:
● from: The collection to use for lookup in the same database
● localField: The field in the primary collection that can be used as a
unique identifier in the from collection.
● foreignField: The field in the from collection that can be used as a
unique identifier in the primary collection.
● as: The name of the new field that will contain the matching
documents from the from collection.
Syntax :
$lookup:
from: < "from collection" >,
localField: < any field from "input collection" >,
foreignField: < any field from "from collection" >,
as: < attached array field >
}}
Ex :
var data = await category.aggregate([
$lookup:{
from:'sub_products',
localField:'_id',
foreignField:'category_id',
as:"subdata"
])
var data = await category.aggregate([
$match:{
'product_name': 'dell'
}
},
$lookup:{
from:'sub_products',
localField:'_id',
foreignField:'category_id',
as:"subdata"
])
var data = await category.aggregate([
$match: {
'_id': new mongoose.Types.ObjectId(req.params.id)
},
$lookup: {
from: 'sub_products',
localField: '_id',
foreignField: 'category_id',
as: "subdata"
} ])
❖Status code
1. Informational Responses: Codes 100 to 199
100 : CONTINUE
101 : SWITCHING PROTOCOL
102 : PROCESSING
103 : EARLY HINTS
2. successful Responses: Codes 200 to 299
200 : OK
201 : CREATED
202 : ACCEPTED
204 : NO CONTANT
206 : PARTIAL CONTANT
3. Redirection Messages: Codes 300 to 399
300 : MULTIPLE CHOICES
301 : MOVES PERMANENTLY
304 : NOT MODIFIED
307 : TEMPORARY REDIRECT
308 : PERMANENT REDIRECT
4. Client Error Responses: Codes 400 to 499
400 : BAD REQUESTS
401 : UNAUTHORISED
403 : FORBIDDEN
404 : NOT FOUND
409 : CONFLICT
5. Server Error Responses: Codes 500 to 599
500 : INTERNAL SERVER ERROR
501 : NOT IMPLEMENTED
502 : BAD GATEWAY
503 : SERVICE UNAVAILABLE
504 : GATEWAY TIMEOUT
❖Error Handling :
Try...Catch Blocks: You can use try...catch blocks to catch and handle
synchronous errors that occur within a specific section of your code. For
example
try{
// Code that may throw an error
catch(err argument)
// Handle the error here
❖Bcrypt hash
bcrypt is a password hashing function designed by Niels Provos and
David based on the Blowfish cipher and presented at USENIX in 1999
Skywin123 => k0kSxuFxfuakd0kf9xyT0KKIGSJwFa
Step 1 : npm I bcrypt
Example :
try{
var newpassword = await bcrypt.hash(req.body.password , 12)
const newobj = ({
name : req.body.name,
password : newpassword
})
data = await br.create(newobj)
res.status(201).json({
status:'success',
data
})
console.log(data);
catch(error){
console.log(error);
❖Bcrypt compare
try {
var name = req.body.name
var password = req.body.password
var find = await br.find({ name: name })
var [find] = find
var newpassword = await bcrypt.compare(req.body.password,
find.password)
console.log(newpassword, 'find');
if (name == find || newpassword == true) {
res.status(201).json({
status: 'success login'
})
console.log('success');
else {
res.status(401).json({
status: 'error not login’)}
console.log('error’); }
catch (error) {console.log(error); }
})
❖Send mail using node js
- The nodemailer module makes it easy to send mail from your
computer.
- The nodemailer module can be downloaded and installed using
npm
Step 1 : open your browser
Step 2 : go to manage your google account
Step 3 : security => on your two step verification => app password
Step 4 : select app => other => name your project => copy key => done
Step 5 : send mail in node js search on google => require path
Step 6 : write code
Step 7 : paste your password and gmail
❖Event loop
- An event loop is an endless loop, which waits for tasks, executes
them, and then sleeps until it receives more tasks.
- The event loop allows us to use callbacks and promises.
- Node.js is a single-threaded event-driven platform that is capable
of running non-blocking, asynchronous programming.
- The event loop executes the tasks starting from the oldest first.
Ex :
console.log('first statement');
setTimeout(()=>{
console.log('second statement');
},2000)
setTimeout(()=>{
console.log('third statement');
},0)
console.log('finish');
❖Callback function
- Node. js callbacks are a special type of function passed as an
argument to another function.
- Callback function is always throw some messages
- A callback is a function that is called when a task is completed
Ex:
setTimeout(() => {
console.log('Callback as Arrow Function');
}, 1000);
setTimeout(function () {
console.log('Callback as Standard Function');
}, 1000);
❖Middleware
- Middleware is commonly used to perform tasks like body parsing
for URL-encoded or JSON requests, cookie parsing for basic cookie
handling, or even building JavaScript modules on the fly
- Middleware functions are the functions that access the request and
response object (req, res) in request-response cycle.
- A middleware function can perform the following tasks:
- It can execute any code.
- It can make changes to the request and the response objects.
- It can end the request-response cycle.
- Middleware is only use for route
- It can call the next middleware function in the stack.
Middleware types
- Application level middleware
- Router-level middleware
- Error-handling middleware
- Built-in middleware
- Third-party middleware
- Application level middleware ex :
const express = require('express')
const app = express();
const reqfilter =(req , res, next)=>{
if(!req.query.age)
{ res.send('please enter age')
else if(req.query.age < 18)
res.send('you can not access this page')
else
{
next();
app.use(reqfilter)
app.get('/' , (req,res)=>{
res.send('home page')
})
app.get('/user', (req , res)=>{
res.send('user page')
})
app.listen(3000)
Route level middleware
const express = require('express')
const app = express()
const filter = (req , res , next) =>{
if(!req.query.age)
{
res.send('not done insert query')
else if(req.query.age<18 )
res.send(' you are under age')
else
next();
app.get('/' , function(req ,res){
res.send('hello skywin this is home page')
})
app.get('/get', filter, function(req , res){
res.send('hello skywin this is get pages')
})
app.get('/about', function(req , res){
res.send('hello skywin this is about pages')
})
app.listen(3030)
❖Token
- Json web token is a standard used to create access tokens for an
application
- It works this way the server generates a token that certifies the user
identity ans sends it to the client
- Step 1 : install express-generator –e
- Step 2 : make a schema
- Step 3 : install json web token
- Step 4 : require jsonwebtoken file
- Ex : var token = jwt.sign({ id: data._id }, 'abc');
- var decoded = jwt.verify(req.headers.token, 'abc');
- Create token and verify token
❖Multer
- Multer is a node.js middleware for handling multipart/form-data,
which is primarily used for uploading files. It is written on top of a
busboy for maximum efficiency.
- Multer will not process any form which is not multipart
(multipart/form-data)
- Step 1 : install express-generator
- Step 2 : install multer , nodemon , mongoose
- Step 3 : make a schema
Define a storage
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'public/images')
},
filename: function (req, file, cb) {
cb(null, file.originalname)
})
const upload = multer({ storage: storage})
router.post('/', upload.single('file'), async function(req, res, next) {
console.log(req.file.originalname)
});
❖.env
- Dotenv is a zero-dependency module that loads environment
variables fr om a .env file into process.env. Storing configuration in
the environment separate from code is based on The Twelve-Factor
App methodology.
Step 1 : install express generator
Step 2 : install mongoose and nodemon
Step 3 : make a schema
Step 4 : install env
Step 5 : create new file .env
Step 6 : and make a connection
Step 7 : require env file
Step 8 : use the config function
❖Socket IO
- Socket.IO is an event-driven library for real-time web applications.
- Socket.IO is a library that enables low-latency, bidirectional and
event-based communication between a client and a server.
- It is built on top of the WebSocket protocol and provides additional
guarantees like fallback to HTTP long-polling or automatic
reconnection.
- socket.io, a real-time communication engine to build network
applications.
- It enables real-time, bi-directional communication between web
clients and servers.
Installation Command
Step 1 : npm i
Step 2 : npm init -y
Step 3 : npx express-generator -e
Step 4 : npm install socket.io
Step 5 : create new file socket.js
Socket.js ex:
const io = require("socket.io")()
const ioObj = {
io:io
}
io.on('connection', (socket) => {
console.log('a user connected');
socket.on("hello" , (data)=>{
console.log(data);
io.emit("receivedmessages",(data))
})
});
module.exports = ioObj
Www file
Step 1 : require socke.js file in www file
Step 2 : use attach function
Ex:
const { io } = require("../socketApi")
io.attach(server)
React File Setup
Step 1 : install react package
Step 2 : npm i socket.io-client
import { io } from 'socket.io-client'
const socket = io.connect("http://localhost:5000")
function App() {
const hello = () => {
console.log("Hello World");
socket.emit("sendMesaage", { name: "parthiv" })
socket.on("recieveMessage", (data)=>{
console.log(data);
}) }
return (
<div className="App">
<button onClick={hello}>Send</button> </div>
);