Skip to content

Commit

Permalink
Node Tut
Browse files Browse the repository at this point in the history
  • Loading branch information
samriddhitiwary committed Sep 21, 2024
1 parent 2e80ca8 commit 19f437c
Show file tree
Hide file tree
Showing 2,152 changed files with 441,138 additions and 0 deletions.
19 changes: 19 additions & 0 deletions .eslintric.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"extends": ["airbnb", "prettier", "plugin:node/recommended"],
"plugins": ["prettier"],
"rules": {
"prettier/prettier": "error",
"spaced-comment": "off",
"no-console": "warn",
"consistent-return": "off",
"func-names": "off",
"object-shorthand": "off",
"no-process-exit": "off",
"no-param-reassign": "off",
"no-return-await": "off",
"no-underscore-dangle": "off",
"class-methods-use-this": "off",
"prefer-destructuring": ["error", { "object": true, "array": false }],
"no-unused-vars": ["error", { "argsIgnorePattern": "req|res|next|val" }]
}
}
53 changes: 53 additions & 0 deletions App.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
const fs = require('fs');
var express = require('express');
var app = express();
app.use(express.json());
const tours = JSON.parse(fs.readFileSync(`${__dirname}/dev_data/tours-simple.json`));

app.get('/api/v1/tours', (req, res) => {
res.status(200).json({
status: 'success',
results:tours.length,
data: {
tours

}
});
});


app.get('/api/v1/tours/:id', (req, res) => {
const id=req.params.id*1;

const tour=tours.find(el=> el.id ===id)
res.status(200).json({
status: 'success',
data:{
tour
}
});
});

app.post('/api/v1/tours', (req,res)=>{
// console.log(req.body);
const newId=tours[tours.length-1].id+1;
const newTour=Object.assign({id:newId},req.body);
tours.push(newTour);

fs.writeFile(`${__dirname}/dev_data/tours-simple.json`, JSON.stringify(tours),err=>{
res.status(201).json({
status:'success',
data:{
tour:newTour
}
});


} );

// res.send('DONE');
})

var server = app.listen(5000, function () {
console.log('Node server is running..');
});
1 change: 1 addition & 0 deletions TEXT/TestFile.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
This is test file to test fs module of Node.js
1 change: 1 addition & 0 deletions TEXT/append.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
HELLO
3 changes: 3 additions & 0 deletions TEXT/output.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
This is what we know about node: This is test file to test fs module of Node.js
.
Create on blah blah
1 change: 1 addition & 0 deletions TEXT/start.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
read-this-file
5 changes: 5 additions & 0 deletions config.env
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
NODE_ENV=development
PORT=5000
DATABSE=mongodb+srv://samriddhitiwary01:<'PASSWORD'>@cluster0.t8kby.mongodb.net/Natours
DATABSE_LOCAL=mongodb://localhost:27017/Natours
DATABSE_PASSWORD=aDq9Ql5z7ay1Jv0c
57 changes: 57 additions & 0 deletions dev_data/data.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
[
{
"id": 0,
"productName": "Fresh Avocados",
"image": "🥑",
"from": "Spain",
"nutrients": "Vitamin B, Vitamin K",
"quantity": "4 🥑",
"price": "6.50",
"organic": true,
"description": "A ripe avocado yields to gentle pressure when held in the palm of the hand and squeezed. The fruit is not sweet, but distinctly and subtly flavored, with smooth texture. The avocado is popular in vegetarian cuisine as a substitute for meats in sandwiches and salads because of its high fat content. Generally, avocado is served raw, though some cultivars, including the common 'Hass', can be cooked for a short time without becoming bitter. It is used as the base for the Mexican dip known as guacamole, as well as a spread on corn tortillas or toast, served with spices."
},
{
"id": 1,
"productName": "Goat and Sheep Cheese",
"image": "🧀",
"from": "Portugal",
"nutrients": "Vitamin A, Calcium",
"quantity": "250g",
"price": "5.00",
"organic": false,
"description": "Creamy and distinct in flavor, goat cheese is a dairy product enjoyed around the world. Goat cheese comes in a wide variety of flavors and textures, from soft and spreadable fresh cheese to salty, crumbly aged cheese. Although it’s made using the same coagulation and separation process as cheese made from cow’s milk, goat cheese differs in nutrient content."
},
{
"id": 2,
"productName": "Apollo Broccoli",
"image": "🥦",
"from": "Portugal",
"nutrients": "Vitamin C, Vitamin K",
"quantity": "3 🥦",
"price": "5.50",
"organic": true,
"description": "Broccoli is known to be a hearty and tasty vegetable which is rich in dozens of nutrients. It is said to pack the most nutritional punch of any vegetable. When we think about green vegetables to include in our diet, broccoli is one of the foremost veggies to come to our mind. Broccoli is a cruciferous vegetable and part of the cabbage family, which includes vegetables such as Brussel sprouts and kale. Although the tastes are different, broccoli and these other vegetables are from the same family."
},
{
"id": 3,
"productName": "Baby Carrots",
"image": "🥕",
"from": "France",
"nutrients": "Vitamin A, Vitamin K",
"quantity": "20 🥕",
"price": "3.00",
"organic": true,
"description": "The carrot is a root vegetable that is often claimed to be the perfect health food. It is crunchy, tasty and highly nutritious. Carrots are a particularly good source of beta-carotene, fiber, vitamin K, potassium and antioxidants. Carrots have a number of health benefits. They are a weight loss friendly food and have been linked to lower cholesterol levels and improved eye health."
},
{
"id": 4,
"productName": "Sweet Corncobs",
"image": "🌽",
"from": "Germany",
"nutrients": "Vitamin C, Magnesium",
"quantity": "2 🌽",
"price": "2.00",
"organic": false,
"description": "Also known as maize, corn is one of the most popular cereal grains in the world. Popcorn and sweet corn are commonly eaten varieties, but refined corn products are also widely consumed, frequently as ingredients in foods. These include tortillas, tortilla chips, polenta, cornmeal, corn flour, corn syrup, and corn oil. Whole-grain corn is as healthy as any cereal grain, rich in fiber and many vitamins, minerals, and antioxidants."
}
]
1 change: 1 addition & 0 deletions dev_data/tours-simple.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
[{"id":0,"name":"The Forest Hiker","duration":5,"maxGroupSize":25,"difficulty":"easy","ratingsAverage":4.7,"ratingsQuantity":37,"price":397,"summary":"Breathtaking hike through the Canadian Banff National Park","description":"Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.\nLorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.","imageCover":"tour-1-cover.jpg","images":["tour-1-1.jpg","tour-1-2.jpg","tour-1-3.jpg"],"startDates":["2021-04-25,10:00","2021-07-20,10:00","2021-10-05,10:00"]},{"id":1,"name":"The Sea Explorer","duration":7,"maxGroupSize":15,"difficulty":"medium","ratingsAverage":4.8,"ratingsQuantity":23,"price":497,"summary":"Exploring the jaw-dropping US east coast by foot and by boat","description":"Consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\nIrure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.","imageCover":"tour-2-cover.jpg","images":["tour-2-1.jpg","tour-2-2.jpg","tour-2-3.jpg"],"startDates":["2021-06-19,10:00","2021-07-20,10:00","2021-08-18,10:00"]},{"id":2,"name":"The Snow Adventurer","duration":4,"maxGroupSize":10,"difficulty":"difficult","ratingsAverage":4.5,"ratingsQuantity":13,"price":997,"summary":"Exciting adventure in the snow with snowboarding and skiing","description":"Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua, ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum!\nDolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur, exercitation ullamco laboris nisi ut aliquip. Lorem ipsum dolor sit amet, consectetur adipisicing elit!","imageCover":"tour-3-cover.jpg","images":["tour-3-1.jpg","tour-3-2.jpg","tour-3-3.jpg"],"startDates":["2022-01-05,10:00","2022-02-12,10:00","2023-01-06,10:00"]},{"id":3,"name":"The City Wanderer","duration":9,"maxGroupSize":20,"difficulty":"easy","ratingsAverage":4.6,"ratingsQuantity":54,"price":1197,"summary":"Living the life of Wanderlust in the US' most beatiful cities","description":"Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat lorem ipsum dolor sit amet.\nConsectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur, nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat!","imageCover":"tour-4-cover.jpg","images":["tour-4-1.jpg","tour-4-2.jpg","tour-4-3.jpg"],"startDates":["2021-03-11,10:00","2021-05-02,10:00","2021-06-09,10:00"]},{"id":4,"name":"The Park Camper","duration":10,"maxGroupSize":15,"difficulty":"medium","ratingsAverage":4.9,"ratingsQuantity":19,"price":1497,"summary":"Breathing in Nature in America's most spectacular National Parks","description":"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.\nDuis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum!","imageCover":"tour-5-cover.jpg","images":["tour-5-1.jpg","tour-5-2.jpg","tour-5-3.jpg"],"startDates":["2021-08-05,10:00","2022-03-20,10:00","2022-08-12,10:00"]},{"id":5,"name":"The Sports Lover","duration":14,"maxGroupSize":8,"difficulty":"difficult","ratingsAverage":4.7,"ratingsQuantity":28,"price":2997,"summary":"Surfing, skating, parajumping, rock climbing and more, all in one tour","description":"Nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.\nVoluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur!","imageCover":"tour-6-cover.jpg","images":["tour-6-1.jpg","tour-6-2.jpg","tour-6-3.jpg"],"startDates":["2021-07-19,10:00","2021-09-06,10:00","2022-03-18,10:00"]},{"id":6,"name":"The Wine Taster","duration":5,"maxGroupSize":8,"difficulty":"easy","ratingsAverage":4.5,"ratingsQuantity":35,"price":1997,"summary":"Exquisite wines, scenic views, exclusive barrel tastings, and much more","description":"Consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\nIrure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.","imageCover":"tour-7-cover.jpg","images":["tour-7-1.jpg","tour-7-2.jpg","tour-7-3.jpg"],"startDates":["2021-02-12,10:00","2021-04-14,10:00","2021-09-01,10:00"]},{"id":7,"name":"The Star Gazer","duration":9,"maxGroupSize":8,"difficulty":"medium","ratingsAverage":4.7,"ratingsQuantity":28,"price":2997,"summary":"The most remote and stunningly beautiful places for seeing the night sky","description":"Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.\nLorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.","imageCover":"tour-8-cover.jpg","images":["tour-8-1.jpg","tour-8-2.jpg","tour-8-3.jpg"],"startDates":["2021-03-23,10:00","2021-10-25,10:00","2022-01-30,10:00"]},{"id":8,"name":"The Northern Lights","duration":3,"maxGroupSize":12,"difficulty":"easy","ratingsAverage":4.9,"ratingsQuantity":33,"price":1497,"summary":"Enjoy the Northern Lights in one of the best places in the world","description":"Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua, ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum!\nDolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur, exercitation ullamco laboris nisi ut aliquip. Lorem ipsum dolor sit amet, consectetur adipisicing elit!","imageCover":"tour-9-cover.jpg","images":["tour-9-1.jpg","tour-9-2.jpg","tour-9-3.jpg"],"startDates":["2021-12-16,10:00","2022-01-16,10:00","2022-12-12,10:00"]},{"id":9,"name":"Test Tour","duration":10,"difficulty":"easy"},{"id":10,"name":"SAMRIDDHI","duration":10,"difficulty":"easy"}]
16 changes: 16 additions & 0 deletions index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<!-- <!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<form action="/submit-student-data" method="post">
First Name: <input name="firstName" type="text" /> <br />
Last Name: <input name="lastName" type="text" /> <br />
<input type="submit" />
</form>
</body>
</html> -->

96 changes: 96 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
const hello="Hello World";
// console.log(hello);

const fs=require('fs');
const textIn=fs.readFileSync('./TEXT/TestFile.txt','utf-8');

const replaceTemp=(temp,product)=>{
let output=temp.replace(/{%PRODUCTNAME%}/g,product.productName);
output=output.replace(/{%IMAGE%}/g,product.image);
output=output.replace(/{%PRICE%}/g,product.price);
output=output.replace(/{%FROM%}/g,product.from);
output=output.replace(/{%NUTRIENTS%}/g,product.nutrients);
output=output.replace(/{%QUANTITY%}/g,product.quantity);
output=output.replace(/{%DESCRIPTION%}/g,product.description);
output=output.replace(/{%ID%}/g,product.id);

if(!product.organic)
output=output.replace(/{%NOT_ORGANIC%}/g,'not-organic');

return output;


}
// console.log(textIn);

// const textOut=`This is what we know about node: ${textIn}.\nCreate on blah blah`;
// fs.writeFileSync('./TEXT/output.txt',textOut);
// console.log("File Written!");

// fs.readFile('./TEXT/start.txt','utf-8',(err,data1)=>{
// fs.readFile(`./TEXT/${data1}.txt`,'utf-8', (err, data2)=>{
// console.log(data2);
// fs.readFile('/TEXT/append.txt', 'utf-8', (err, data3)=>{
// console.log(data3);

// fs.writeFile('./TEXT/final.txt',`${data2}\n${data3}`,'utf-8',err=>{
// console.log('Your file has been written');

// })

// })
// })
// })

const http=require('http');
const path = require('path');
const url=require('url');

const temp_Overview=fs.readFileSync(`${__dirname}/templates/template-overview.html`, 'utf-8');
const temp_Card=fs.readFileSync(`${__dirname}/templates/template-card.html`, 'utf-8');
const temp_product=fs.readFileSync(`${__dirname}/templates/template-product.html`, 'utf-8');

const data=fs.readFileSync(`${__dirname}/dev_data/data.json`,'utf-8');
const dataObj=JSON.parse(data);




const server=http.createServer((req,res)=>{
// const pathname=req.url;

const { query, pathname } = url.parse(req.url, true);


if(pathname ==='/' || pathname==='/overview'){
res.writeHead(200,{'Content-type':'text/html'});

const carsdsHtml=dataObj.map(el=> replaceTemp(temp_Card,el)).join('');
const output=temp_Overview.replace('{%PRODUCT_CARDS%}',carsdsHtml);
res.end(output);
}


else if(pathname === '/product'){
res.writeHead(200,{'Content-type':'text/html'});
const product= dataObj[query.id];
const output=replaceTemp(temp_product,product);
res.end(output);
}


else if(pathname === '/api'){
fs.readFile(`${__dirname}/dev_data/data.json`, 'utf-8', (err,data)=>{
res.end(data);
})
}

else{
res.writeHead(404);
res.end('PAGE NOT FOUND');
}
});

server.listen(8000,'127.0.0.1',()=>{
console.log('Listening to requests on port 8000');
});
4 changes: 4 additions & 0 deletions jsFile/Data.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
module.exports = {
firstName: 'James',
lastName: 'Bond'
}
17 changes: 17 additions & 0 deletions jsFile/Event.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// // get the reference of EventEmitter class of events module
// var events = require('events');

// //create an object of EventEmitter class by using above reference
// var em = new events.EventEmitter();

// //Subscribe for FirstEvent
// em.on('click', function (data) {
// console.log(data);
// });

// em.on('OpenTheDoor', function (data) {
// console.log(`I opened the door`);
// });

// // Raising FirstEvent
// em.emit('StoreInFridge', 'Package of Milk');
18 changes: 18 additions & 0 deletions jsFile/Express.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
var express = require('express');
var app = express();
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: false }));

app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});

app.post('/submit-student-data', function (req, res) {
var name = req.body.firstName + ' ' + req.body.lastName;
res.send(name + ' Submitted Successfully!');
});


var server = app.listen(3000, function () {
console.log('Node server is running..');
});
17 changes: 17 additions & 0 deletions jsFile/Log.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// var log = {
// info: function (info) {
// console.log('Info: ' + info);
// },
// warning:function (warning) {
// console.log('Warning: ' + warning);
// },
// error:function (error) {
// console.log('Error: ' + error);
// }
// };

// module.exports = log

module.exports.log = function (msg) {
console.log(msg);
};
6 changes: 6 additions & 0 deletions jsFile/Message.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
// module.exports = 'Hello world';
exports.SimpleMessage = 'Hello world';

// //or

// module.exports.SimpleMessage = 'Hello world';
7 changes: 7 additions & 0 deletions jsFile/Person.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
// module.exports = function (firstName, lastName) {
// this.firstName = firstName;
// this.lastName = lastName;
// this.fullName = function () {
// return this.firstName + ' ' + this.lastName;
// }
// }
Loading

0 comments on commit 19f437c

Please sign in to comment.