Using Node's core http module

While we have used restify to create this simple service, there are several alternative approaches that we could have used, such as:

Let's create an alternative implementation using the Node core HTTP module. We'll copy the micro folder to micro-core-http and alter the service.js file in the micro-core-http/adderservice folder to the following:

const http = require('http')

const server = http.createServer(respond)

server.listen(8080, function () {
console.log('listening on port 8080')
})

function respond (req, res) {
const [cmd, first, second] = req.url.split('/').slice(1)
const notFound = cmd !== 'add' ||
first === undefined ||
second === undefined

if (notFound) {
error(404, res)
return
}

const result = parseInt(first, 10) + parseInt(second, 10)
res.end(result)
}

function error(code, res) {
res.statusCode = code
res.end(http.STATUS_CODES[code])
}

We can start our service, as in the main recipe, with:

$ node service.js 

We can use curl as before to test our service:

$ curl http://localhost:8080/add/1/2 

While using the core http module can give us the same results, we have to implement additional lower level logic. Neglecting edge cases or misunderstanding fundamentals can lead to brittle code. The framework support provided by the restify module also supplies us with conveniences such as parameter parsing, automated error handling, middleware support, and so forth.

Node's core http module
For more on Node's core http module, and support for other web protocols take a look at Chapter 5, Wielding Web Protocols
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset