Last active
August 29, 2015 14:25
-
-
Save SergeyNarozhny/322ffb63d6d44a28cac6 to your computer and use it in GitHub Desktop.
NodeJS simple middleware logger
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
#logger.js | |
module.exports = function(request, response, next) | |
{ | |
var start = +new Date(), | |
stream = process.stdout, | |
url = request.url, | |
method = request.method; | |
response.on("finish", function(){ | |
var duration = +new Date() - start, | |
message = method + ' to ' + url + '\nytook ' + duration + ' ms \n\n'; | |
stream.write(message); | |
}); | |
next(); | |
} | |
#app.js | |
var express = require("express"), | |
app = express(), | |
logger = require("./logger"), | |
bodyParser = require('body-parser'), | |
parseUrlencoded = bodyParser.urlencoded({ extended: false }); | |
app.use(logger); | |
app.use(express.static('public')); | |
app.param('name', function(req, res, next){ | |
var name = req.params.name, | |
block = name[0].toUpperCase() + name.slice(1).toLowerCase(); | |
req.blockName = block; | |
next(); | |
}); | |
app.route("/blocks") | |
.get(function(req, res){ | |
var blocks = req.blockName || ['Book1', 'Book2', 'Book3']; | |
res.json(blocks); | |
}) | |
.post(parseUrlencoded, function(req, res){ | |
var newBlock = req.body, | |
blocks[newBlock.name] = newBlock.description; | |
res.status(201).json(newBlock.name); | |
}); | |
app.listen(3000, function(){ | |
console.log('listening ') | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment