Skip to content

Instantly share code, notes, and snippets.

@bnb
Created June 28, 2014 00:40
Show Gist options
  • Save bnb/19e404d7b8f3dd726b3c to your computer and use it in GitHub Desktop.
Save bnb/19e404d7b8f3dd726b3c to your computer and use it in GitHub Desktop.
Why does this not work when running `node blog_recent.3.js`?
var http = require('http');
var fs = require('fs');
var server = http.createServer(function (req, res) {
getTitles(res);
}).listen(8000, "127.0.0.1");
function getTitles(res) {
fs.readFile('./titles.json', function (err, data) {
if (err) return hadError(err);
getTemplate(JSON.parse(data.toString(), res));
});
}
function getTemplate(titles, res) {
fs.readFile('./template.html', function (err, data) {
if (err) return hadError(err);
formatHTML(titles, data.toString(), res);
});
}
function formatHTML(titles, tmpl, res) {
var html = tmpl.replace('%', titles.join('</li><li>'));
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(html);
}
function hadError (err, res) {
console.error(err);
res.end('Red alert! Server error!');
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>Latest Posts</h1>
<ul><li>%</li></ul>
</body>
</html>
[
"JSON breaks the latest XML speed recorrds",
"Node.js voted greatest programming language ever",
"Go programmers pissed off about Node"
]
@HiroatuHidaka
Copy link

function getTitles(res) {
fs.readFile('./titles.json', function (err, data) {
if (err) return hadError(err);
getTemplate(JSON.parse(data.toString(), res));
});
}
change to
function getTitles(res) {
fs.readFile('./titles.json', function (err, data) {
if (err) return hadError(err);
getTemplate(JSON.parse(data.toString()), res);
});
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment