CoolFace
Modelpublic

deepak0318/node_js_basics

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
app.js285 linesDownload Raw Back to root
1const fs=require('fs');2const http=require('http');3const url=require('url')4const replacehtml=require('./Modules/replacehtml')5const events=require('events')6const user=require('./Modules/user')7 8const html=fs.readFileSync('./Template/index.html','utf-8')9 10let products=JSON.parse(fs.readFileSync('./Data/products.json','utf-8'))11let productlisthtml=fs.readFileSync('./Template/product-list.html','utf-8');12let productdetailhtml=fs.readFileSync('./Template/product-details.html','utf-8')13 14// let producthtmlarray=products.map((product)=>{15//     let output=productlisthtml.replace('{{%IMAGE%}}',product.productImage);16//     output = output.replace('{{%NAME%}}', product.name);17//     output = output.replace('{{%MODELNAME%}}', product.modeName);18//     output = output.replace('{{%MODELNO%}}', product.modelNumber);19//     output = output.replace('{{%SIZE%}}', product.size);20//     output = output.replace('{{%CAMERA%}}', product.camera);21//     output = output.replace('{{%PRICE%}}', product.price);22//     output = output.replace('{{%COLOR%}}', product.color);23//     output = output.replace('{{%ID%}}', product.id);24//     output = output.replace('{{%ROM%}}', product.ROM);25//     output = output.replace('{{%DESC%}}', product.Description);26//     return output27// })28 29// function replacehtml(template,product){30//     let output=template.replace('{{%IMAGE%}}',product.productImage);31//     output = output.replace('{{%NAME%}}', product.name);32//     output = output.replace('{{%MODELNAME%}}', product.modeName);33//     output = output.replace('{{%MODELNO%}}', product.modelNumber);34//     output = output.replace('{{%SIZE%}}', product.size);35//     output = output.replace('{{%CAMERA%}}', product.camera);36//     output = output.replace('{{%PRICE%}}', product.price);37//     output = output.replace('{{%COLOR%}}', product.color);38//     output = output.replace('{{%ID%}}', product.id);39//     output = output.replace('{{%ROM%}}', product.ROM);40//     output = output.replace('{{%DESC%}}', product.Description);41//     return output42// }43 44// const server=http.createServer((request,response)=>{45//     let {query,pathname:path}=url.parse(request.url,true)46//     // console.log(x); pathname stored in path47//     // if true query string will pass if false query string will not pass48//     // let path=request.url;    // ==  /49//     if(path==='/' || path.toLowerCase()==='/home'){50//         response.writeHead(200,{51//             'Content-Type':'text/html',52//             'my-header':'Hello,world'53//         });54//         response.end(html.replace('{{%CONTENT%}}',"you are in hom page"));55//     }56//     else if(path.toLowerCase()==='/about'){57//         response.writeHead(200,{58//             'Content-Type':'text/html',59//             'my-header':'Hello,world'60//         });61//         response.end( html.replace('{{%CONTENT%}}',"you are in about page"))62//     }63//     else if(path.toLowerCase()==='/contact'){64//         response.writeHead(200,{65//             'Content-Type':'text/html',66//             'my-header':'Hello,world'67//         });68//         response.end( html.replace('{{%CONTENT%}}',"you are in contact page"))69//     }70//     else if(path.toLowerCase()==='/products'){71//         response.writeHead(200,{72//             // 'Content-Type':'application/json'  then output is html code73//             'Content-Type':'text/html'74//         })75//         // fs.readFile('./Data/products.json','utf-8',(error,data)=>{76//         //     let products=JSON.parse(data)77//         //     response.end(data);78//         // })79//         // every time clicking this will execute take more time80//         if(!query.id){81//             let producthtmlarray=products.map((prod)=>{82//                 return replacehtml(productlisthtml,prod);83//                 // if no return it will not update from next loop84//             })85//             let productresponsehtml=html.replace('{{%CONTENT%}}',producthtmlarray.join(','))86//             //because it is array of productlisthtml87//             response.end(productresponsehtml)88//         }89//         else{90//             let prod=products[query.id]91//             //deatils of product based on id stored in array92//             let productdetailresponsehtml=replacehtml(productdetailhtml,prod)93//             response.end(html.replace('{{%CONTENT%}}',productdetailresponsehtml));94//         }95       96//     }97//     else{98//         response.writeHead(404,{99//             'Content-Type':'text/html',100//             'my-header':'Hello,world'101//         });102//         response.end(html.replace('{{%CONTENT%}}',"error 404 found"));103//     }104// });105 106const server=http.createServer();107// not emiting request manually here event emitted by server object 108// server.on('request',(request,response)=>{109//     let {query,pathname:path}=url.parse(request.url,true)110//     // console.log(x); pathname stored in path111//     // if true query string will pass if false query string will not pass112//     // let path=request.url;    // ==  /113//     if(path==='/' || path.toLowerCase()==='/home'){114//         response.writeHead(200,{115//             'Content-Type':'text/html',116//             'my-header':'Hello,world'117//         });118//         response.end(html.replace('{{%CONTENT%}}',"you are in hom page"));119//     }120//     else if(path.toLowerCase()==='/about'){121//         response.writeHead(200,{122//             'Content-Type':'text/html',123//             'my-header':'Hello,world'124//         });125//         response.end( html.replace('{{%CONTENT%}}',"you are in about page"))126//     }127//     else if(path.toLowerCase()==='/contact'){128//         response.writeHead(200,{129//             'Content-Type':'text/html',130//             'my-header':'Hello,world'131//         });132//         response.end( html.replace('{{%CONTENT%}}',"you are in contact page"))133//     }134//     else if(path.toLowerCase()==='/products'){135//         response.writeHead(200,{136//             // 'Content-Type':'application/json'  then output is html code137//             'Content-Type':'text/html'138//         })139//         // fs.readFile('./Data/products.json','utf-8',(error,data)=>{140//         //     let products=JSON.parse(data)141//         //     response.end(data);142//         // })143//         // every time clicking this will execute take more time144//         if(!query.id){145//             let producthtmlarray=products.map((prod)=>{146//                 return replacehtml(productlisthtml,prod);147//                 // if no return it will not update from next loop148//             })149//             let productresponsehtml=html.replace('{{%CONTENT%}}',producthtmlarray.join(','))150//             //because it is array of productlisthtml151//             response.end(productresponsehtml)152//         }153//         else{154//             let prod=products[query.id]155//             //deatils of product based on id stored in array156//             let productdetailresponsehtml=replacehtml(productdetailhtml,prod)157//             response.end(html.replace('{{%CONTENT%}}',productdetailresponsehtml));158//         }159       160//     }161//     else{162//         response.writeHead(404,{163//             'Content-Type':'text/html',164//             'my-header':'Hello,world'165//         });166//         response.end(html.replace('{{%CONTENT%}}',"error 404 found"));167//     }168// });169 170 171 172 173server.listen(8000,'127.0.0.1',()=>{174    console.log('Server Started');175})176 177//EVENTS178 179//create instance of event emitter class call its constructor180// using thsi we can emit an event181// let myemitter=new events.EventEmitter();182// // using emit method we can emit a named event userCreate and we need to listen it again183 184// // event listner should first after event emittter then it can listen185 186// myemitter.on('userCreated',(id,name)=>{187//     console.log(`a new user ${name} with id ${id} is created`);188// })189 190// myemitter.on('userCreated',(id,name)=>{191//     console.log(`a new user ${name} with id ${id} is added in database`);192// })193 194 195 196// myemitter.emit('userCreated',101,'Deepak');197 198 199// let myemitter=new user();200 201// myemitter.on('userCreated',(id,name)=>{202//     console.log(`a new user ${name} with id ${id} is created`);203// })204 205// myemitter.on('userCreated',(id,name)=>{206//     console.log(`a new user ${name} with id ${id} is added in database`);207// })208 209// myemitter.emit('userCreated',101,'Deepak');210 211//READING212 213// server.on('request',(req,res)=>{214//     fs.readFile('./Files/large-file.txt',(err,data)=>{215//         if(err){216//             res.end("Something went wrong");217//             return;218//         }219//         res.end(data);220//     })221//     // if data is more take more time to read and execute so app crashes222// })223 224 225// server.on('request',(req,res)=>{226//     let rs=fs.createReadStream('./Files/large-figrle.txt');227//     rs.on('data',(chunk)=>{// to listen data it is compulsory228//         res.write(chunk);// end not use because it means there is no dtaa to write229//         // res.end();// there is no data to write230//         //user no need to wait to get all data231//     })232 233//     //when no chunk is there then end event will execute234 235//     res.on('end',()=>{236//         res.end();237//     })238 239 240 241//     //if error occur242//     rs.on('error',(errors)=>{//if error ocuur event occur and stored in errors243//         res.end(errors.message);244//     })245 246//     //back presuure writable stream on client not work as fast as read stream works247// })248 249// PIPE METHOD250// server.on('request',(req,res)=>{251//     let rs=fs.createReadStream('./Files/large-file.txt');252//     // we can use pipe on read stream only253//      rs.pipe(res);254//      //pipe is used to pipe output of readable stream and input of writable stream255//      // it solve back pressure and handle speed of data coming256// })257 258console.log("hi");259 260//STORED IN FIRST PHASE261 262 263// SECOND PHASE- of event loop but it take time to read so it not go to callback queue264fs.readFile('./Files/input.txt',()=>{265    console.log('File read complete');266 267    setTimeout(()=>{268        console.log("Timer call executed");269    },1000);270 271    setImmediate(()=>{272        console.log('SetImmediate callback executed');273    })274 275    process.nextTick(()=>{276        console.log("next tick")277    })278})279 280//STORED IN THIRD PHASE281//execute,expire  immediately there is no time limit it expires immediately282//setimmediate expires after execution of timeout. but sometimes it fails as bug in node js283 284 285console.log("Programm has completed");