Skip to content
Snippets Groups Projects
Commit 6e6f6586 authored by Gunananthaa K B's avatar Gunananthaa K B
Browse files

added basic cache

parent a64bc870
Branches
No related tags found
No related merge requests found
......@@ -2,6 +2,7 @@ const http = require('http');
const PORT = 8080;
// filtering
const filter = request=>{
if(request.url==='/good'){
return true;
......@@ -9,23 +10,42 @@ const filter = request=>{
return false;
}
let cache = ``;
let lastModified=null;
const requestListener = (req,res)=>{
const options = {
hostname:'localhost',
port:3000,
path:'/'
path:'/',
headers: {
'If-Modified-Since': `${JSON.stringify(lastModified)}`
}
};
if(filter(req)){
const get = http.get(options,response=>{
console.log(`statusCode: ${response.statusCode}`);
let buffer="";
response.on('data',d=>{buffer+=d});
response.on('error',err=>{console.log(`error:${err}`)});
response.on('end',()=>{
if(response.statusCode===304){
res.setHeader("Content-Type", "text/html");
res.writeHead(200);
res.end(buffer);
});
res.end(cache);
}
else{
let buffer="";
// console.log(`Last modified: ${JSON.stringify(response.headers['last-modified'] )}`);
lastModified = new Date(JSON.parse(response.headers['last-modified']));
console.log(`Last modified; ${lastModified}`);
response.on('data',d=>{buffer+=d});
response.on('error',err=>{console.log(`error:${err}`)});
response.on('end',()=>{
cache=buffer;
res.setHeader("Content-Type", "text/html");
res.writeHead(response.statusCode);
res.end(buffer);
});
}
});
}
else{
......
......@@ -2,12 +2,20 @@ const http = require('http');
const fs = require('fs').promises;
const PORT = 3000;
const lastModified=(new Date()).toJSON();
const requestListener = (req,res)=>{
fs.readFile('./contents/index.html').then(contents=>{
if(req.headers['if-modified-since'] && req.headers['if-modified-since']===JSON.stringify(lastModified)){
res.setHeader("Last-Modified",`${JSON.stringify(lastModified)}`);
res.writeHead(304);
res.end("Not applicable");
}
else{fs.readFile('./contents/index.html').then(contents=>{
res.setHeader("Content-Type", "text/html");
res.setHeader("Last-Modified",`${JSON.stringify(lastModified)}`);
res.writeHead(200);
res.end(contents);
});
});}
console.log(req.headers);
}
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment