Created
August 25, 2015 17:38
-
-
Save bennett000/a9fe6f15fdb141fb66be to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* This gist is not recommended to be used for anything, other than | |
* an example for a story about old school hit counters, and the | |
* complexity of "dynamic" web pages vs static web pages. | |
*/ | |
var http = require('http'), | |
fs = require('fs'); | |
http.createServer(onHTTPReq).listen(8000); | |
function startCount(next) { | |
write(0, function onStartWrite(err) { | |
if (err) { | |
next(err); | |
return; | |
} | |
next(null, 0); | |
}); | |
} | |
function read(next) { | |
fs.readFile('./count', 'utf-8', function callbackNumber(err, val) { | |
if (!err) { | |
next(null, +val); | |
return; | |
} | |
if (err.code === 'ENOENT') { | |
startCount(next); | |
} else { | |
next(err); | |
} | |
}); | |
} | |
function write(val, next) { | |
fs.writeFile('./count', val, next); | |
} | |
function increment(next) { | |
read(function onIncRead(err, val) { | |
if (err) { | |
next(err); | |
return; | |
} | |
val = +val || 0; | |
val += 1; | |
write(val, function (err) { | |
if (err) { | |
next(err); | |
return; | |
} | |
next(null, +val); | |
}); | |
}); | |
} | |
function serverError(req, res, err) { | |
res.writeHead(500, {'Content-Type': 'text/plain'}); | |
res.end('Fatal Error ' + err.message); | |
} | |
function notFound(req, res) { | |
res.writeHead(404, {'Content-Type': 'text/plain'}); | |
res.end(['Sorry', req.url, 'Not Found.'].join(' ')); | |
} | |
function onHTTPReq(req, res) { | |
if (req.url !== '/') { | |
notFound(req, res); | |
return; | |
} | |
increment(function onIncrement(err, val) { | |
if (err) { | |
serverError(req, res, err); | |
return; | |
} | |
res.writeHead(200, {'Content-Type': 'text/plain'}); | |
res.end('Visits: ' + val); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment