finalhandler: HTTP Final Responder

2.1.1 · active · verified Tue Apr 21

finalhandler is a Node.js utility function designed to standardize the final steps of an HTTP request within a server or middleware chain. It gracefully handles both successful completion (responding with a 404 for unhandled requests) and error scenarios, ensuring that the `ServerResponse` object is properly concluded and the `IncomingMessage` stream is unpiped. Currently at version 2.1.1, the library maintains an active development and maintenance cadence, with recent updates in both its v1 and v2 major versions. Its primary differentiation lies in providing a low-level, unopinionated mechanism for robust error and 404 response handling, including options for custom error logging, making it a foundational component for web frameworks like Express and Connect.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to use `finalhandler` to set up a basic HTTP server that serves a file, logging any errors to the console using the `onerror` option, and responding with appropriate HTTP status codes.

const finalhandler = require('finalhandler');
const fs = require('fs');
const http = require('http');

const server = http.createServer((req, res) => {
  const done = finalhandler(req, res, { onerror: logerror });

  fs.readFile('index.html', (err, buf) => {
    if (err) return done(err);
    res.setHeader('Content-Type', 'text/html');
    res.end(buf);
  });
});

server.listen(3000, () => {
  console.log('Server listening on port 3000');
});

function logerror (err) {
  console.error('Error encountered:', err.stack || err.toString());
}

// To make this runnable, create a dummy index.html
// For example, echo '<h1>Hello World!</h1>' > index.html

view raw JSON →