how to use another page urls from running page and how to create router |, rest api ain nodejs nodejstututorials

 u already seen this below code in above programms or previus posts


create router folder 

in thgat create productRouter.js


const express = require('express');
const app = express();
var mongoose= require("mongoose");
var Persons=require("../models/personSchema,js");

var productRouter = express.Router();

var bodyParser = require('body-parser');

productRouter.use(bodyParser.json());

productRouter.route('/')
.get(function (req,res)
{
Persons.find({}, function(err,person)
{
if(err) throw err;
res.json(person);
})
})

module.exports= productRouter;


in index.js

import and use this file

var productRouter = require('./router/productRouter');


use

app.use('/products', productRouter);

http://localhost:3000/products/


if u hit this api - u can get

all the things in product page













statemanagement in nodejs | nodejs tutorials

staetemenage storing cooking to identify users 

state management
one client make request with web form
client requested data send to backend
then it will responds
but requested data not tehre
to store taht data
we use statemanagement

we will use different type of module to use statemanagement

sm has two major parts
client side- client side manage management
server side- it is called as servr side management

client side - cookies
serverside - sessions



register teh cookie and remove the cookie using get method api

stored to browser cokokie



i not entered any expiry data
so it will remove automatically whenever browser closed

in below programm set the cookie and remove the cookie


var express = require('express');
var cookieParser = require('cookie-parser');

var app = express();
app.use(cookieParser());

app.get('/',
function (req,res)
{
res.cookie('mycookie', 'tutorials point video tutorials');
res.end('hi there');
}

);

app.get('/remove',
function (req,res)
{
res.clearCookie("mycookie");
res.end('hi there');
}

);

app.listen(8081,
function () {
console.log("server started");
});


encrypt cookie

app.use sesion - secret - encryt, save initialise- if u not do any change in cokokie in their time it will be like original
when login is done - it will false
max age is 60000 milli seconds






var express = require('express');
var cookieParser = require('cookie-parser');
var session= require("express-session");
var morgan = require("morgan");

var app = express();

app.use(morgan('dev'));
app.use(cookieParser());
app.use(session({secret: 'secretkey', saveUnitialised:true, resave: true, cookie: {maxAge: 60000}}));

app.get('/',
function (req,res,next)
{
if(req.session.views)
{
req.session.views++;
res.setHeader('Content-Type','text/html')
res.write('<p> views:' + req.session.views +'</p>')
res.write('<p> expires in:' + (req.session.cookie.maxAge / 1000) +'</p>')
res.end()
}
else {
req.session.views=1
res.end('refresh page')
}
}

);

app.listen(8081,
function () {
console.log("server started");
});


ist prints in browser 
prints 
refresh 
after refresh 
taht count increses


after one idle minute - no refresh - session expires


it will show refresh


 

nodejs middlewares | nodejs tutorials

 with use we  can use middleware


in below 

code

middleware- whenever before process actualt request - middlewre acts as mediator - if it passes

whenever reaches home url

it calls log and hello function 

because it ats as middleare in this

when log call bcak function it printes log

when hello function it prints hello

 


next means -  go back to api , after log , calls next middleware

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

app.get("/", log, hello);

function log(req, res, next)
{
console.log("log started");
next();
}
function hello(req, res, next)
{
console.log("hello started");
next();
}

app.listen(8081,
function () {
console.log("server started");
});

node js get and post request from html page | nodejs tutorials

const express = require('express');
const app = express();
app.use(express.static('public'));

public means

//use method will be use whenever wanna make middlewares im our applications, middlewares will be used before responding requiest (mediator between request and before respond)
//routing ist auth - then controler - in auth is mediatior
// we create a folder called public, inside this we will place a style sheet, javascrpt, fonts, images we will place at public

one seperate directory for images,javascript files, css file that called as scaffolding

npm install express-generator -g

to make public folders

 get api with star

app.get("/*list",(req,res,next) =>
{
let person="department listing"
res.send(person);
}
);

personlist or any thing before list 


api process_get

json stringfy - combine response

app.get("/process_get",(req,res,next) =>
{
response=
{
first_name :req.query.first_name,
last_name :req.query.last_name
};
res.end(JSON.stringify(response));

}
);


post api

let bodyParser = require('body-parser');

var urlencodedParser= bodyParser.urlencoded({ extended: true });

post api needs url encoded and body-parser 

urlencodedParesr - is like middleware

before api


app.post("/process_post",urlencodedParser,
function (req,res)
{
response=
{
first_name :req.body.first_name,
last_name :req.body.last_name
};
res.end(JSON.stringify(response));

}
);

post is from aoi or html form


api get form 

app.get("/form",(req,res,next) =>
{
res.sendFile(__dirname + "/" + "one.html");

}
);

one.html

<form method="POST" action="http://localhost:8081/process_post">

<input type ="text" name="first_name">
<input type ="text" name="last_name">
<input type="submit" name="submit">
</form>


after submit post in above html form 

it will reach process_post

takes taht data from post data and combine as stringify


connect to server

using below 

var server = app.listen(8081,
function () {
var host= server.address().address;
var port= server.address().port;
console.log("listening at http://%s:%s", host,port);
});










node js network programming | nodejs tutorials

 tcp 

node js server programming using tcp

on socket - we will host our applicaitons

and at the other end on telnet - we wil  raise request

telnent transfered by tcp to socket - raise teh request - resolve at asocket


for this purpose we import net

create  a server with socket


server.js

var net = require("net");
console.log('vamsi');
var server = net.createServer(function(socket)
{
socket.end("Hello and good bye");
}

);

server.on("error", function(error){
if(error.code ==='EADDRINUSE')
{
console.error("port is already in use");
}
})
server.listen(1234, function (){
console.log("server started");
});


if server is on 

it below programm run otherwise port is not running like that areror  displays

var net = require("net");

var client = net.connect(
{
port :1234,
host: "localhost",
}, function (){
console.log("connection establieshd");
}
);

client.js





conenct to port 1234


in bleow programming

after server started

connected print

then at aclient side write json messange on client side

if any change in file modfication time 

fs.watch - it watch continuosly

if modified - write 

changed  into file 

if client is disconnected it will print disconected


fs.watch

connectin.write

connection.on

server.js
 


run node server.js data.txt

it will write int data.text

file


node client.js

write into file

echo >>data.txt

conect between client and server




node js filestream | node js tutorials

 _filename

_dirname

above are two glabal varialbe

_dirname - it prints current directoru

_filename - it printes current location 

process.cwd()

current working directory

process.chdir("") change directory



 



join path and string

path.sep = console = /

directories.join(path.sep);



how to base name from path

how to get ext from path

path.extname(filename)

path.basename(filename)





how to get absolute path

path.resolve(_dirname,'content','subfolder','test.txt')
users/smilga/desktop/tutorial/content/subfolder/test.txt

how to check file exists and 
red file write file then rename the file

fs is one module
var fs= require('fs');
var path= _dirname +"/mytext.txt";

fs.readFile(path, "utf8" function(error,data)

read the file in that path and then encrypt with utf8 then callback the function
i



how to rename the fuile

fs.rename



make new directory



read all the data in directory
fs.readdir(path, function (error,files){




remove directory
fs.rmdir




const {readFileSync,writeFileSync} = require('fs');

read the file 
const first = readfilesync('pathname','utf8');
write into file
write from another files too

writefilesync('path','hellow world : ${first}, ${second}',{flag:'a'})

flag new line

 

flag a means append
 


create server , console the data from file

it wil print the whole data its in mbs if it is a larage file


fs.craetereadstream


same size in ui but in response headers , transfer-encoding - chunked






readfile('path',(){})
call back function with arguments
readfile('path',(err,result){
    if(err)
{
    console.log(err)
return
}
console.log(result)
})

without utf8



readfile('path','utf8',(err,result){
    if(err)
{
    console.log(err)
return
}
console.log(result)
const first : result
writeFIle('path','here $(furst)',(err,resulte)=>{})
})

write file



read and write into same file



whats the difference between read file and read file sync

if async- if a function takes time - taht function execute late, whichone execute first that one wil execute
before excute of readfiile sync console works
but line by line works which one take large time that throw to last time means it runs on sepaerately
if it works over it prints immedieatly

next line not stop for before line
sync




async
readFile



with promise
now below works as sync
means when this called it must return becaue of promise  (call back)
till that next line waits






const start = async() => {}
call back in async funciton
const start = async() => {
const first = await getText('./content/first.txt');
console.log(first);

}
in try catch
one function for number of file paths
const start = async() => {
try{
const first = await getText('./content/first.txt');
const second = await getText('./content/second.txt');
console.log(first);
}catch(error)[
console.log(error)
}

}
 


calling above function - invoke
start();

instead of writing get text function seperate use
util

util is a ibuilt funciton




without util and with promises

 




in above thing, if read one file that file data write to another fileif the next funciton in next line , its not wokrs because it is async
so for that purpose in call back we write another funciion like below












node js eror handling

 in normal programing we willl use try catch

but in node js different

including a domain module

whatever programmin gin domain module

if any error caught - it will print 






get one from mongodatabase using node js via api | nodejs tutorails

get one usng findone



app.get('/get-one-await',async (req, res)=> {
let params = req.query.id;
let listDetails= await PERSON_SCHEMA.findOne({id:params}).sort({_id:-1});
res.send(listDetails);
})

app.get('/get-by-id',async (req, res)=> {
let body = req.body;
PERSON_SCHEMA.find({fname: {$eq: body.name}}).then(result =>
{
res.send(result)
}).catch(err => {
res.send("faile")
})
})
app.get('/get-by-id-one',async (req, res)=> {
let body = req.body;
PERSON_SCHEMA.findOne({fname: {$eq: body.name}}).then(result =>
{
res.send(result)
}).catch(err => {
res.send("faile")
})
})

http://localhost:3000/get-by-id-one 


 







get data from databse using api and mongo db | nodejs tutorials

api


http://localhost:3000/get

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

PERSON_SCHEMA.find().then(result =>
{
res.send(result)
}).catch(err => {
res.send("faile")
})
})



app.get('/get-await',async (req, res)=> {

let listDetails= await PERSON_SCHEMA.find({});
res.send(listDetails);
})

 

how to insert multiple records using post man api| nodejstutorials

using below method

u can insert many records at a time using one api

create many api

app.post('/create-many',async (req, res)=> {
let body = req.body;

PERSON_SCHEMA.insertMany(body).then(result =>
{
res.send({sts:200,msg:'created'})
}).catch(err => {
res.send("faile")
})
})


post man data

api http://localhost:3000/create-many

[

{
"fname": "one",
"lname": "onel",
"mno": "one mobile",
"addr": "one addr"
},
{
"fname": "two",
"lname": "twol",
"mno": "two mobile",
"addr": "two addr"
},
{
"fname": "two",
"lname": "twol",
"mno": "two mobile",
"addr": "two addr"
},
{
"fname": "two",
"lname": "threel",
"mno": "three mobile",
"addr": "three addr"
}
]

hit on api it willl insert into databse


how to install mongodb compass in ubuntu 20.04| mongodb nodejs tutorials

 


wget https://downloads.mongodb.com/compass/mongodb-compass_1.21.1_amd64.deb
sudo dpkg -i mongodb-compass_1.21.1_amd64.deb
sudo apt --fix-broken install
mongodb-compass


this is the screen visible after sucesful install of mongodb compass

then 

check mongodb status 

 sudo service mongodb status


u canc heck in above screen shot it is active and running


if not start the mongodb

u can see the screen  of mongo db compass , in that see connect button
click on connect button if server is running
if not run the server or give the credentials of onliine server which is running
connected succefully
if u have credentials to connect past in below window
how it gets-> 




it wil shwo whats tables or databses u have already
refresh taht databse if u wanna see updated












AI Tools

 Midjourney oter.ai aiva googlegemin dall-e copilot jasper copilot openaiplayground