finalhandler
's direct dependencies. Data on all dependencies, including transitive ones, is available via CSV download.Name | Version | Size | License | Type | Vulnerabilities |
---|---|---|---|---|---|
debug | 2.6.9 | 16.13 kB | MIT | prod | |
encodeurl | 1.0.2 | 3.18 kB | MIT | prod | |
escape-html | 1.0.3 | 1.87 kB | MIT | prod | |
on-finished | 2.4.1 | 4.93 kB | MIT | prod | |
parseurl | 1.3.3 | 3.86 kB | MIT | prod | |
statuses | 2.0.1 | 4.57 kB | MIT | prod | |
unpipe | 1.0.0 | 2.05 kB | MIT | prod |
Finalhandler is a Node.js function designed to carry out the final step in responding to an HTTP request. It works by returning a function to be invoked as the final step for the respective request and response. This makes the flow of handling requests highly manageable as the final step ensures either a 404 response is written out, or, in the case of any errors, an error response will be dispatched appropriately.
You'll first need to install the finalhandler module using the NPM install command in your terminal. Simply run npm install finalhandler
. Once installed, you can require it in your program as var finalhandler = require('finalhandler')
.
A basic usage example would be the following:
var finalhandler = require('finalhandler')
var http = require('http')
var server = http.createServer(function (req, res) {
var done = finalhandler(req, res)
done()
})
server.listen(3000)
In this case, the server will always return a 404 since no routes are handled. In a more practical scenario, you may want to return a file as the response, for instance, an HTML file:
var finalhandler = require('finalhandler')
var fs = require('fs')
var http = require('http')
var server = http.createServer(function (req, res) {
var done = finalhandler(req, res)
fs.readFile('index.html', function (err, buf) {
if (err) return done(err)
res.setHeader('Content-Type', 'text/html')
res.end(buf)
})
})
server.listen(3000)
Here, we read index.html
and send its content as the response. If any error occurs, done(err)
is called.
The documentation for finalhandler can be found in its NPM package page and the GitHub repository. Links to these locations can be found in the readme. The readme contains explanatory details about the API, options it accepts, and usage examples. It presents clear instructions on installation, function syntax, options that you can pass into the main function, and example code snippets.