Reputation: 14586
In order to keep the code clean I want to avoid using hard-coded values but use pre-defined constants such as HTTP status codes.
I can do it either with:
import {constants as httpConstants} from "http2";
res.sendStatus(httpConstants.HTTP_STATUS_INTERNAL_SERVER_ERROR);
or with an npm-package such as http-status-codes
:
import {StatusCodes} from 'http-status-codes';
res.sendStatus(StatusCodes.INTERNAL_SERVER_ERROR);
Do I understand it correctly that if http2/constants
is a Node.js built-in module which is widely used internally by Node.js, the import of http2/constants
, which is quite big, should not affect the app performance since it is already is in use by Node.js?
Upvotes: 0
Views: 137
Reputation: 106385
All the internal modules (including http2
) are registered when Node starts. Quoting the source:
// A list of built-in modules. In order to do module registration
// in node::Init(), need to add built-in modules in the following list.
// Then in binding::RegisterBuiltinModules(), it calls modules' registration
// function. This helps the built-in modules are loaded properly when
// node is built as static library. No need to depend on the
// __attribute__((constructor)) like mechanism in GCC.
#define NODE_BUILTIN_STANDARD_MODULES(V)
So yes, I'd rather use that module in your case.
By the way, technically HTTP status codes are not even part of http2 module: they're stored in node_http_common.h file as set of macroses:
#define HTTP_STATUS_CODES(V) \
V(CONTINUE, 100) \
V(SWITCHING_PROTOCOLS, 101) \
V(PROCESSING, 102) \
V(EARLY_HINTS, 103) \
V(OK, 200) \
// ...
... and, finally, are connected to http2 module constants
prop in yet another series of #define statements:
#define V(name, _) NODE_DEFINE_CONSTANT(constants, HTTP_STATUS_##name);
HTTP_STATUS_CODES(V)
#undef V
What's funny though is that there's another place in Node storing the same data reversed (status codes are keys, not values): it's http module. Source:
const STATUS_CODES = {
100: 'Continue', // RFC 7231 6.2.1
101: 'Switching Protocols', // RFC 7231 6.2.2
102: 'Processing', // RFC 2518 10.1 (obsoleted by RFC 4918)
103: 'Early Hints', // RFC 8297 2
200: 'OK', // RFC 7231 6.3.1
201: 'Created', // RFC 7231 6.3.2
// ...
Upvotes: 1