KEMBAR78
Node Notws With Examples | PDF | Computing | Software Engineering
0% found this document useful (0 votes)
10 views35 pages

Node Notws With Examples

Node.js is an open-source, cross-platform runtime environment for executing JavaScript outside of the browser, primarily used for backend development. It features a single-threaded model with event looping, a vast package ecosystem via npm, and asynchronous capabilities, making it efficient for real-time applications. The document covers various aspects of Node.js, including modules, global objects, the file system, HTTP module, and built-in modules like URL and OS.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views35 pages

Node Notws With Examples

Node.js is an open-source, cross-platform runtime environment for executing JavaScript outside of the browser, primarily used for backend development. It features a single-threaded model with event looping, a vast package ecosystem via npm, and asynchronous capabilities, making it efficient for real-time applications. The document covers various aspects of Node.js, including modules, global objects, the file system, HTTP module, and built-in modules like URL and OS.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

NODE JS

Introduction
➢ Node JS is a runtime environment which allow JavaScript to execute outside the browser
➢ With the help of node JS we can create networking web application
➢ Node JS mainly used for backend purpose
➢ Node JS is developed by Ryan dehl in 2009
➢ Node JS is open source, cross platform runtime environment
➢ Node JS is asynchronous in nature

Feature
1. Single Tread
• Node JS follow single thread model with event looping
2. Cross platform
• It means that software or application can run on multiple os without change
major code
3. Very fast
• Build in google chrome’s V8 engine so its library is very fast in code execution
4. Huge package ecosystem
• Node JS include node package manager to manager that access to millions of
reusable packages for free
5. Easy to understand
6. Asynchronous in nature

Advantages of Node JS
1. Cost effective with fullstack JS
2. Helps to building cross-platform application
3. High performance for real-applications
4. Easy to learn and quick to adapt
5. Reduce loading time
REPL (Read, Evaluate, Print, Loop)
➢ REPL stand for read, evaluate, print, loop
➢ It is mainly used for testing purpose
➢ To start REPL simply running node on Command prompt

Node Module
NPM(node package manager)
➢ NPM stand for node package manager
➢ NPM used for manager the third party open source packages
➢ It is command line interface app automatically come with node JS

Modules
➢ Set of function is called as module
➢ Reusable block of code is called as module
➢ Module is same like a library in JavaScript
➢ To include the module we use require() method or function with named of module ways
➢ There are 3 type of module
1. Core module
2. Build-in module: fs, http, path, os, dns, net, url etc……..
3. Third-party module

Global Object
➢ It is an object which are accessible in application from anywhere without importing
➢ No need to import it before use
➢ Following are different global object
A. __dirname
B. __filename
C. Console
D. Process
E. Buffer
F. Settimeout
1] __dirname:
➢ return the name of directory where we currently contain code
➢ example

console.log("Directory name is ----------> ",__dirname)

2] __filename:
➢ specifies filename of code being executed
➢ example

console.log("file name: ",__filename);

3]console:

➢ used to show the message to user on console


➢ it has different method
1. log()
2. error()
3. warn()
4. time()
5. timeend()
6. table()

// A]console.log()
console.log("Hello how are You");

// B] console.error()
console.error("Error mssage")

// C] console.warn()
console.warn("console.warn object")

// D] console.table
console.table([["Akshay", "Sandip", "Sam", "Suraj", "Dhiraj"], [1, 2, 3, 4, 5]])

// E] timeEnd
console.timeEnd("8")
Process
➢ It is global object used to provide the information about the currently running process
➢ Example

// console.log(process)
console.log(process.pid);
console.log(process.version);
console.log(process.ppid);

buffer
➢ buffer is class used to deal with binary data
➢ it is temporary raw chunk of data

let buffer = Buffer.from("Akshay")


console.log(buffer);

stream
➢ stream is flow of data
➢ stream is sequence of data that is being move from one point to another over time
➢ following are the type of stream
1. readable stream
2. writeable stream
3. transform stream
4. duplex stream

1] Readable Stream:

➢ used to read data use the Readable Stream


➢ example
let fs = require("fs")

let readablestream = fs.createReadStream("./output.txt","utf-8")

// ADD EVENT
readablestream.on('data',chank=>{ // IT IS AN EVENT LISTENER THAT LISTENS
FOR DATA EVENT
console.log(chank);

})
console.log(fs);

2] writeable Stream
➢ Used to write operation
➢ example
let writestream = fs.createWriteStream("./write.txt","utf-8")

readablestream.on('data',chunk=>{
console.log("successfully run chunk");

writestream.write(chunk,err=>{
if (err) throw err
console.log("successfully Written");
console.log(chunk);
})

})

let str = "i am learning node js"


writestream.write(str,err=>{
if (err) throw err

console.log("data written succesfully..........");

})
Build-In module
1] FS module
➢ Fs stand for file system
➢ Fs module is used to work with file system on your computer
➢ Two ways to work with FS module
a. Asynchronous
b. Synchronous

Asynchronous Synchronous

Task are not executed one by one Task are executed one by one
If any task take time to execute then Wait for execute task which take time
execute next task instead of wait for to execute
execute
Used for fetching data from server, Used for perform simple operation
reading file etc
Faster for I/O operation Slower for I/O operation

1] Synchronous way
Method
1] readFileSync()
➢ Used to read file
➢ Syntax
Fs.readFileSync(path,character_encoder)

const fs = require("fs")

let readdata = fs.readFileSync("write.txt")

console.log(readdata.toString())

console.log("Data read succesfully.......");


2] writeFileSync()
➢ Used to write file in synchronous way
➢ Syntax
Fs.writeFileSync(path,text)

const fs = require("fs")

let p = "i clrear my intervirew and now i want to learn Nodejs"

fs.writeFileSync("output.txt",p)

console.log("write data sucessfully...........");

3] mkdirSync()
➢ Use to create directory
➢ Syntax
Fs.mkdirSync(foldername)
const fs = require("fs")

if (!fs.existsSync("Qspider")) {
let dir = fs.mkdirSync("Qspider")
console.log(dir);
console.log("folder Created succefully");
} else {
console.log("folder Already exits...........");
}

4] unlinkSync()
➢ Used to delete file
➢ Syntax
Fs.unlinkSync(path)
const fs = require("fs")

fs.unlinkSync("write.txt")
console.log("deleted sucessfuly........");

5] rmdirSync()
➢ Used to remove the directory
➢ Syntax
Fs.rmdirSync(path)
const fs = require("fs")

fs.rmdirSync("Qspider")
console.log("deleted succesfuly..");

6] renameSync()
Used to rename file
Syntax
Fs.renameSync(oldname,newname)
const fs = require("fs")

fs.renameSync("output.txt","new.txt")

7] appendFileSync()
➢ Used to append the data in existing file
➢ Syntax
Fs.appendFileSync(path,data)
const fs = require("fs")

fs.appendFileSync("new.txt","util not i learn basic function of FS module")

console.log("data append succefully...");

Asynchronous way
➢ To overcome synchronous, we have to use asynchronous way

1] readFile()
➢ Used to read file
➢ Syntax
Fs.readFile(path,code-uncoder,callback function)

fs.readFile("write.txt",(err,data)=>{
if(err) throw err
console.log("Fetch data is : ",data.toString());
console.log("data fetch sucessfully");
})
console.log("operation done");

2] writeFile()
➢ Used to write file in Asynchronous way
➢ Syntax
Fs.writeFileSync(path,data,callback_function)

fs.writeFile("output.txt","hello hi how are you",(e)=>{


if(e) throw e
console.log("data write sucessfully........");
})
console.log("done........");
3] mkdir()
➢ Use to create directory
➢ Syntax
Fs.mkdir(foldername,callback_func)

try {
fs.mkdir("qspider1", (err) => {
if (err) {
console.log(err);
}
console.log("Directory created...");

})

} catch (error) {
console.error("folder Already exits...........", error);
}

4] unlink()
➢ Used to delete file
➢ Syntax
Fs.unlink(path,callback_func)

fs.unlink("./qspider/abc.txt",(err)=>{
if(err)
throw err

console.log("file deleted succesfully........");

})

console.log("done!!");
5] rmdir()
➢ Used to remove the directory
➢ Syntax
Fs.rmdir(path,callback_func)

fs.rmdir("qspider1",(err)=>{
if (err){
console.log("Error occure..")
return
}

console.log("deleted............");

})

console.log("done.........");

6] rename()
Used to rename file
Syntax
Fs.rename(oldname,newname,callback_func)

fs.rename("new.txt", "new1.txt", (e) => {


if (e) throw e

console.log("rename done.........");

})
7] appendFile()
➢ Used to append the data in existing file
➢ Syntax
Fs.appendFile(path,data,callback_func)

fs.appendFile("new1.txt","hello hi how are youlearn appendfile function using


asynchronuous",(e)=>{
if(e)
{
console.log("error............");
}
console.log("Data will be added.......");

})
console.log("operation done......");

Http module
➢ http stands for hypertext transfer protocol
➢ http module is used to create server and handle the http request and response
➢ http module is built in module in node JS allow to create http server that listen to server
port & gives response to client
➢ method
1] createServer():-
✓ with the help of createServer() method we can create the http server it will
accept a callback function which fired each time a new request and hits server
✓ syntax
http.CreateServer((req,res)=>{
})
✓ to send back the response to client we use res.send or use res.end method

2] listen()

o Used to listen incoming request from client


o With the help of listen we can start server
o Syntax
Server.listen(port,callback())

import http from 'http'


// server created
const server = http.createServer((req,res)=>{
res.end("hello how are you")
console.log("Server Created........");
})

//server running
server.listen(5000,err=>{
if (err) throw err
console.log("server running on Port 5000 .....");
})

Short way to create server


// Short way to create server
http.createServer((req,res)=>{
res.end("Learn node js")
}).listen(4000,err=> console.log(err,"server is running........."))

Working with different URL


const server = http.createServer((req, res) => {
if (req.url === "/about") {
res.write("<h1>About Page</h1>")
res.end()
return
}
if (req.url === "/carrer") {
res.write("<h1>Carrer Page</h1>")
res.end()
return
}
res.write("<h1>Server is created</h1>")
res.end()

}).listen(4000, err => console.log("server running............"))


To serve API

http.createServer((req, res) => {


// create the array object
let emp = [
{
name:"Akshay",
salary:"5000",
id:1
},

{
name:"Karan",
salary:"5000",
id:23
},

{
name:"Sam",
salary:"8000",
id:15
},
]
res.setHeader("Content-type", "application/json") // setHeader
res.end(JSON.stringify(emp)) // convert OBJ into the Json
}).listen(5000,err=>{
if(err)
throw err
console.log("Server is running............");

})

To render Audio and video


http.createServer((req, res) => {
res.setHeader("Content-type", "video/mp4")
let video = fs.readFileSync("vi.mp4")

res.send(video)

}).listen(4000, err => console.log("server running.........."))


URL Module
✓ It is a built in module used to split up web address into readable parts
✓ It provides the utilities for URL resolution & parsing
✓ Method
1. Hash() : set & get fragment portion
2. Host () : set & get host portion
3. Hostname ():- set & get host name portion
4. Protocol()
5. Search ()
6. ToString()
7. Tojson()

const { log } = require("console")


const url = require("url")

const reqobj = 'http://localhost:9000/user?country=india&city=delhi#mumbai'

const urlobj = url.parse(reqobj)

console.log(urlobj);

//1] HASH : USED TO SET & GET FRAGEMENT PORTION OF URL


console.log(urlobj.hash);

// 2] HOST : USED TO SET OR GET HOST PORTION OF A URL


console.log(urlobj.host)

// 3] HOSTNAMES: USE TO SET OR GET THE HOSTNAME PORTION OF URL


console.log(urlobj.hostname);

// 4]protocol : USED TO SET OR GET THE PROTOCOL OF URL


console.log(urlobj.protocol);

// 5] USED TO SET OR GET THE SEARCH PORTION OF URL


console.log(urlobj.search);

// 6] href: UE TO SET OR GET HREF OF URL


console.log(urlobj.href);

import url from 'url'


import http from 'http'
import fs from 'fs'
const server = http.createServer((req,res)=>{

const urlobj = url.parse(req.url)


console.log((urlobj));

const fn = "."+urlobj.pathname

console.log(fn);

fs.readFile(fn,(err,data)=>{

res.setHeader('content-type','text/html')

res.end(data)
})

})
server.listen(5000,()=>{
console.log("server is running........");

})

OS module
➢ It is a built in module in node js
➢ Used to provides all the information about the computer operating system ‘
➢ Method
1] Os.platform()
Return os name like mac or ubuntu etc …
2] os.networkInterface()
Return IP4 and IP6 address or all information regarding the IP

3] os.hostname ()
Return the host name

4] os.userInfo()
Return object name of computer

const os = require('os')

console.log(os);

// arch : return archtechure of an os


console.log(os.arch());

// platform : used to return the name of os system


let operatingSyatem = os.platform()

if('win32' == operatingSyatem || 'win64' == operatingSyatem){


console.log("APplication can run");
}

// userInfo() ; used to return onject name of computer


console.log(os.userInfo());

// hostname() : return host name


console.log(os.hostname());

// networkInterface() : return inforation about it ip address


console.log(os.networkInterfaces());

// totalmem : used to find the total memory


console.log(os.totalmem());

console.log(os.freemem());

console.log("used memery", os.totalmem - os.freemem);


PATH module
✓ Path is a build in module which provides the utilities for working with file directory path
✓ Method
1. Basename(): return last portion of path
2. Dirname(): return directory name of path
3. Extname(): return extension of path
4. Join(): join all given path segments together using separator
5. Normalize(): normalizes given path

EVENT module
✓ Build in module in node js
✓ Using event module, we can create, fire & listen for your own events
✓ Event provide class called event emitter using which we can create our own events
✓ Two ways to create events
✓ Two ways to create events
1. By using constructor
2. By using extends keyword

// path is a build in module in node js used to provides utilities for work with
file and directory path

const path = require("path")

// console.log(path);

// 1]BASENAME : RETURN LAST PORTION OF PATH


console.log(path.basename(__filename));
console.log(path.basename(__dirname));
// 2] DIRNAME : RETURN DIRECTORY NAME
console.log(path.dirname(__dirname));

// 3] extname: return extention of path


console.log(path.extname(__filename));

// 4] join : used to segement all path together using seperator


console.log(path.join(__filename,"/","index.php"));

// 5] normalize : normilize given path used normalize method


console.log(path.normalize(__filename));

//6] resolve : used to resolve the absolute path


console.log(path.resolve("baout.html../..../..."));

// 7] isAbsolute : return true if path is absulute


console.log(path.isAbsolute(__dirname));

DNS MODULE
✓ It is a build in module in node js
✓ It contains method to get information of given hostname
✓ DNS module enable name resolution
✓ Method
1. Getservers():return an array of IP address String
2. Lookup()
3. Resolve4()
4. Resolve6()
5. Resolve()
6. Resolvetext()

const DNS = require("dns")


console.log(DNS);

// 1] getServers() : return array of ip address string


console.log(DNS.getServers());

// lookup() : resolve the host name


DNS.lookup('www.google.com', (err, address, family) => {
console.log('address: %j family: IPv%s', address, family);
});

NODE TIMER
✓ This are the global function where don’t need to use require function to import
✓ Set timer function
1. SetImmediate()
2. setInterval()
3. setTimeout()
✓ Clear timer function
1. Clearimmediate()
2. clearInterval()
3. clearTimeout()

// 1] setImmediate() : excute immediatly after the created


setImmediate(()=>{
console.log("Set Immediate timer function");
})

// 2]setTimeout : execute after the perticular time of interval only once


setTimeout(()=>{
console.log("set Timeout function");
},4000)

// setInterval: excute again and again after the particular time interval
setInterval(()=>{
console.log("setInterval timer");
},2000)

// clear timer

String decoder
✓ Used to decode buffer into string
✓ It is similar to buffer.tostring() but provide extra support to UTF
✓ StringDecoder class has two method
1. Decoder.write(buffer): it is used to return decoded string
2. Decoder.end():return trailing bytes if any left in buffer

// string decoder : used to decode the buffer infon string


const sd = require("string_decoder")

console.log(sd);

const decoder = new sd.StringDecoder("utf-8")


const buffer = new Buffer.from("this is node js poject")
console.log(decoder.write(buffer))

QueryString
✓ It is module used to provides utilities for formatting URL queryString
✓ Used to convert query string into JSON object
✓ It is global object so need to install it explicitly
✓ Used npm install queryString to install queryString
✓ Methods
1. Parse(): parses querystring & return an object
2. Stringfy(): stringfy an object & return a query string

// query String : used to provide the utilities for formating the url query
string
const url = require('url')
const qs = require('querystring');
const { log } = require("console");

let exampleUrl ="localhost:4000?name=akshay&id=12&add=pune"

let urlParse = url.parse(exampleUrl)


console.log(urlParse);

let query = qs.parse(urlParse.query)


console.log(query);

console.log("Name of emp ",query.name);


console.log("id of emp ",query.id);
console.log("address of emp",query.add);

NODEMON
✓ Nodemon is tool helps you automatically restart your node.js app whenever you make
changes in code
✓ Helpful to save time during development
✓ Do download globally used npm install –g nodemon
UTIL MODULE
✓ Util is a build in module
✓ It provides helper function that make easier to work with object debug & asynchronous
code
✓ Method
1. Format()
▪ Used to format string
▪ Syntax
Util.format(format,[..args])

2. Inspect()
▪ Return a string representation of an object great for debugging complex
object
▪ Syntax:
Util.inspect(obj,options)

3. Promisify()
▪ Convert callback-based function to return promise
▪ Syntax
Util.promisify(function)

4. Types
▪ Contains type checking function like isDate(), isPromise(), isRegex() etc

// util is build in module is node js used to provide helper functions that make
easy to work with debug , object and asynchrous code

const { log } = require('console');


const util = require('util')

// 1] format : used to format string same like as printf in c


let str = util.format("my name is %s i work in %s and earning %i", "AkshayKumar",
"IBM", 45200)
console.log(str);

// 2] inspect return string represenattion of an object useful for debuging


purpose
let obj = {
name: "Akshay",
salary: 45220,
id: 45,
adds: "pune"
}
const s = util.inspect(obj, { depth: null, colors: true, breakLength: true })
console.log(s);

// 3] types : contains type checking functions like isDate,isPromise,isRegExp


etc.........
let p = new Promise((rel, rej) => {
console.log(rel, rej);

}).then(console.log("resolve")).catch(console.log("rej"))

console.log(util.types.isDate(new Date()));
console.log(util.types.isKeyObject(obj));
console.log(util.types.isPromise(p));

// 4] promisify : used to convert callback based funcion to promise

const fs = require("fs")
const readfile = util.promisify(fs.readFile)
readfile("new.txt",'utf-8').then(console.log("Hello")).catch(console.log("by"))

Express JS

✓ It is framework used in node JS


✓ It is node JS web application framework that provides list of feature for building
web & mobile application easily
✓ When we want to used express in our node JS used following command
NPM INSTALL EXPRESS

Routing in Express JS
✓ Routing means how your application response to different HTTP request to specific URL
endpoint
✓ Types of routing in Node JS
1. Basic routes in express JS
2. Route parameter in express JS
3. Optional & multiple route parameter
4. Route chaining in express JS

Basic routes
✓ Involves defining URL & specifying an HTTP method

const express = require('express')


const fs = require('fs')
const app = express()

//SIMPLE PARAMETER
app.get('/', (req, res) => {
res.end("<h1>Home page</h1>")
console.log(req.method);

})
app.get('/about', (req, res) => {
res.end("<h1>About page</h1>")
console.log(req.method);
})

Route parameter
✓ Route parameters allow capturing dynamic values from URLs
✓ Making routes flexible & reusable
//ROUTE PARAMETER
app.get('/about/:userId', (req, res) => {
res.send(`<h1>user ID : ${req.params.userId}</h1>`)
res.end()
})

Optional & multiple route parameter


✓ Express allows defining optional parameters & multiple parameters in single route
//OPTIONAL & MULTIPLE ROUTE PARAMETER
app.get('/product/:productId', (req, res) => {
res.send(`<h1>Product ID: ${req.params.productId}</h1>`)
})

Multiple route parameters


// muttiple Route Parameter
app.get('/posts/:category/:postId', (req, res) => {
res.send(`Category: ${req.params.category}, Post ID: ${req.params.postId}`);
});

Query parameter in express JS


✓ Query parameters are used for filtering or modifying request
✓ They are appear after ? symbol in URLs
//QUERY PARAMETERS IN EXPRESSJS
app.get('/search', (req, res) => {
res.send(`Search Results for : ${req.params.q}`)
})

Route chaining in express JS


✓ Chaining allow defining multiple handlers for route using route
//ROUTING CHAINNG IN EXPRESS JS
app.route('/users')
.get((req, res) => res.send('Get method'))
.post((req, res) => res.send('post method'))
.put((req, res) => res.send('put method'))
.delete((req, res) => res.send('delete method'))

Route Handlers in Express JS


✓ Route handler define how express response to request

// ROUTE HANDLERS IN EXPRESS JS


app.get('/insta', (res, req, next) => {
console.log("First Handle");
next()
}, (req, res, next) => {
console.log('second handler');
next()
}, (req, res) => {
res.send("Routing handleing in express jss")
}

app.listen(4000, () => {
console.log("server is running..........");
})

Advantages of routing
1. Code organization
Make code structure by managing functionalities separately
2. Readability
It enhances code understanding by clearly defining how URL are handle
3. Scalability
Allows for easy addition of new features without major changes
4. Restful API design
Middleware
✓ Middleware function have access to the request object, response & also next function
✓ It is used to
▪ Change the request or response object
▪ End response-request lifecycle
▪ Call the next middleware
✓ Syntax
App.HTTP_Method(path,(req,res,next)=>{
},(req,res)=>{})

Types of Middleware
1. Application level middleware
2. Route-level middleware
3. Error-handling middleware
4. Build-in middleware
5. Third-party middleware

Application level middleware


✓ The middleware that you define across your whole express application using app.use()
or specific routes is called as application level middleware
✓ Used for
1. Logging every request
2. Checking user authentication
3. Parsing data

const express = require('express')

const app = express()

// Application level middleware : the middle ware which use for whole application
is called as application level Middle ware
app.use((req, res, next) => {
console.log(`${req.method} ${req.url}`);
next()
})
app.get('/', (req, res) => {
res.send(`
<div>
<h1>Application Level Middleware</h1>
<h5>Middleware</h5>
</div>
`)
})

app.use('/admin', (req, res, next) => {


console.log(`${req.method} ${req.url}`);
next()
})

app.get('/admin/dashboards', (req, res) => {


res.send(`
<div>
<h1>Application Level Middleware</h1>
<h1>${req.url}</h1>
<h5>Middleware</h5>
</div>
`)
})

app.get('/admin/dashboards/:age', (req, res) => {


if (req.params.age > 18) {
res.send(`
<div>
<h1>Application Level Middleware</h1>
<h1>${req.url}</h1>
<h5>Middleware</h5>
</div>
`)
}else{
res.send(`
age must be more than 18
`)
}
})
app.listen(4000, () => {
console.log("server running.............");

})

Route level middleware


✓ Route level middleware is middle ware that is executed only for specific route
✓ It useful for
a. To keep your code clean & modular
b. To prevent middleware from running globally
c. To apply logic like authentication, validation or logging only specific routes

const express = require('express')


const ageValidate = require('../middleware/checkAge.js')

const app = express()

app.get("/",(req,res)=>{
res.send("home page")
})

app.get("/about",ageValidate,(req,res)=>{
res.send("about page")
})

app.get("/profile",ageValidate,(req,res)=>{
res.send("profile page")
})

app.listen(4000,()=>{
console.log("seerver running");
})
Application level middleware Route level middleware
Applies to all routes Applies only to specific route
Runs everywhere unless path is filtered Attached to specific route
Use foe logging, global auth, body parsing Used for route specific auth, validation check

Node JS with MYSQL

1] create connection
✓ To create connection with MySQL we use MySQL .createConnection() method
✓ It will take object as argument
✓ Before that we want to download MySQL using
Npm install mysql or npm install mysql2

✓ To execute the query use query method


✓ Syntax
Conn.query(query,callbackfun)

How to connect with database using nodeJS

const mysql = require('mysql2')

const conn = mysql.createConnection({


host:'localhost',
user:'root',
password:'root'
})

conn.connect((err)=>{
if(err)
{
console.log(err);
return

}
console.log("connected with database");
})

Create database

const mysql = require('mysql2')

const conn = mysql.createConnection({


host:'localhost',
user:'root',
password:'root'
})

conn.connect((err)=>{
if(err)
{
console.log(err);
return

}
console.log("connected with database");
conn.query("CREATE DATABASE demo1",(e)=>{
if(e)
{
console.log("Error Ocuure at query level",e);
return
}

console.log("Database Created successfully.....");

})
})

Create table
const mysql = require('mysql2')
const conn = mysql.createConnection({
host: "localhost",
user: 'root',
password: 'root',
database: 'demo1'
})

conn.connect((err) => {

if (err) {
console.log("Error at Connection level");
return
}

console.log("Connected with database");

const queryString = "CREATE TABLE emp(eid int,ename varchar(40),salary int)"

conn.query(queryString, (e) => {


if (e) {
console.log("Error at the query level.......", e);
return
}
})

console.log("table Created successfully");

})

Insert data
const mysql = require('mysql2')

const conn = mysql.createConnection({


host:'localhost',
password:'root',
user:'root',
database:'demo1'
})
conn.connect((err)=>{

if(err){
console.log("Error at connection level.......");
return
}
console.log("Connected with database");

const str = "INSERT INTO EMP(eid,ename,salary) values(1,'Akshay',45200)";

conn.query(str,(err)=>{

if(err){
console.log("error at query level",err);
return
}

console.log("Data insered.......ss");

})

})

Select data

const mysql = require('mysql2')


const conn = mysql.createConnection({
host: "localhost",
user: 'root',
password: 'root',
database: 'demo1'
})
conn.connect((e) => {
if (e) throw e
console.log("connected.......");
const str = "select * from emp";
conn.query(str, (e, data) => {
if (e) throw e
console.log(data);
})

})
Update data
const mysql = require('mysql2')

const conn = mysql.createConnection({


host:"localhost",
password:"root",
user:"root",
database:"demo1"
})

conn.connect((err)=>{

if(err) throw err

console.log("connected.....");

const q = "UPDATE emp SET ename = 'Akshaykumar' where eid = 1 "

conn.query(q,(err)=>{
if(err) throw err
console.log('updated');

})

})

You might also like