What is http-status?
The http-status npm package provides a collection of HTTP status codes and their associated messages. It is useful for setting and interpreting HTTP response statuses in web applications.
What are http-status's main functionalities?
Accessing Status Codes
You can easily access standard HTTP status codes using the package. This is useful for setting response statuses in your web server.
const httpStatus = require('http-status');
console.log(httpStatus.OK); // 200
console.log(httpStatus.NOT_FOUND); // 404
Accessing Status Messages
The package allows you to retrieve the standard message associated with a given status code. This can be useful for logging or displaying human-readable status messages.
const httpStatus = require('http-status');
console.log(httpStatus['200']); // 'OK'
console.log(httpStatus['404']); // 'Not Found'
Custom Status Codes
You can add custom status codes and messages to the http-status object. This is useful if your application uses non-standard status codes.
const httpStatus = require('http-status');
httpStatus['999'] = 'Custom Status';
console.log(httpStatus['999']); // 'Custom Status'
Other packages similar to http-status
statuses
The statuses package provides similar functionality by offering a list of HTTP status codes and their associated messages. It also allows for custom status codes and messages. Compared to http-status, statuses is more lightweight and focuses solely on status codes and messages without additional features.
http-errors
The http-errors package is used to create HTTP error objects with status codes and messages. It provides more advanced error handling capabilities compared to http-status, including the ability to create custom error classes. It is useful for applications that need detailed error handling and reporting.
HTTP Status
Utility to interact with HTTP status code.
Usage
API sample
var HTTPStatus = require('http-status');
// Print "Internal Server Error"
console.log(HTTPStatus[500]);
// Print 500
console.log(HTTPStatus.INTERNAL_SERVER_ERROR);
Express sample
var express = require('express'),
redis = require('redis'),
HTTPStatus = require('http-status');
var app = express.createServer();
app.get('/', function (req, res) {
var client = redis.createClient();
client.ping(function (err, msg) {
if (err) {
return res.send(HTTPStatus.INTERNAL_SERVER_ERROR);
}
res.send(msg, HTTPStatus.OK);
});
});
app.listen(3000);
Contributors