Skip to content

Instantly share code, notes, and snippets.

@arn-ob
Last active July 19, 2017 06:20
Show Gist options
  • Save arn-ob/c671f389a98fa5580dce9260f584150e to your computer and use it in GitHub Desktop.
Save arn-ob/c671f389a98fa5580dce9260f584150e to your computer and use it in GitHub Desktop.
[NodeJs] Reducing nesting by creating Intermediary Function and Also same Function by using calback
//use of callbacks
var http = require('http');
var fs = require('fs');
http.createServer(function(req,res){
if(req.url== '/')
{
fs.readFile('title.json',function(err,data){
if(err){
console.error(err);
res.end('Server Error');
}
else
{
var title = JSON.parse(data.toString());
fs.readFile('ind.html',function(err,data){
if(err){
console.error(err);
res.end('Server Error');
}
else{
var tmpl = data.toString();
var html = tmpl.replace('%',title.join('</li><li>'));
res.writeHead(200, {'Content-Type':'text/html'});
res.end(html);
}
})
}
})
}
}).listen(8000,"127.0.0.1");
<html>
<head>
</head>
<body>
<h1>Latest post </h1>
<ul><li>%</li></ul>
</body>
</html>
//Reducing nesting by creating Intermediary Function
var http = require('http');
var fs = require('fs');
var server= http.createServer(function(req,res){
getTitle(res);
}).listen(8001,"localhost");
function getTitle(res){
fs.readFile('title.json',function(err,data){
if(err){
hadError(err,res);
}else{
getTemplete(JSON.parse(data.toString()),res);
}
})
}
function getTemplete(title,res){
fs.readFile('ind.html', function(err, data){
if(err){
hadError(err,res);
}
else{
formathtml(title,data.toString(),res);
}
})
}
function formathtml(title,tmpl,res){
var html = tmpl.replace('%',title.join('</li><li>'));
res.writeHead(200 , {'Content-type':'text/html'});
res.end(html);
}
function hadError(err,res){
console.error(err);
res.end('Server Error');
}
[
"Hy i am arnob" ,
"How are ypu dpijng",
"gjhghjhjjk"
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment