I am trying to get my hands dirty with some node.js code. I understand the theory of events and callbacks and asynchronous techniques, but this does not mean it is easy to really produce code in "the right manner".
The following is my (reallife) example of a middleware. A simple HTTP server listens for requests and on /get
, it queries our backend and presents the data from there to the client.
var http = require('http')
var https = require('https')
var url = require('url')
var backendOptions = {
port: 1414,
hostname: 'data.backend.com',
path: '/bulk',
auth: 'user:$ecret'
}
var backendGet = function(callback) {
https.get(backendOptions, function(res) {
var content = ''
res.on('data', function(chunk) {
content += chunk
})
res.on('end', function() {
callback(content)
})
})
}
var server = http.createServer(function(req, res) {
switch(url.parse(req.url).pathname) {
case '/get':
backendGet(function(content) {
res.writeHead(200, {'Content-Type': 'text/plain'})
res.write(content)
res.end()
})
break
default:
res.writeHead(200, {'Content-Type': 'text/html'})
res.write('<p>It works!</p>')
res.end()
}
}).listen(8080, 'localhost')
This code works - but is this how I write code in node.js? The client should be served when the data from backend is available, so I'm calling backendGet()
with a function as callback to operate on the res
object as soon as there is no more backend data to be read.
General comments and critique are welcome, too!
Alex