为了保持代码的整洁,我想避免使用硬编码的值,而是使用预定义的常量,如HTTP状态代码。
我可以用以下两种方法:
import {constants as httpConstants} from "http2";
res.sendStatus(httpConstants.HTTP_STATUS_INTERNAL_SERVER_ERROR);或使用npm包(如http-status-codes )。
import {StatusCodes} from 'http-status-codes';
res.sendStatus(StatusCodes.INTERNAL_SERVER_ERROR);我是否正确地理解到,如果http2/constants是一个Node.js内置模块,而Node.js在内部广泛使用,那么导入相当大的http2/constants不应该影响应用程序的性能,因为Node.js已经在使用它了?
发布于 2021-07-03 12:04:49
所有内部模块(包括http2)都是在节点启动时注册的。引用来源
// 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)所以是的,我宁愿在你的情况下使用那个模块。
顺便说一句,从技术上讲,HTTP状态代码甚至不是http2模块的一部分:它们作为宏集存储在common.h文件中:
#define HTTP_STATUS_CODES(V) \
V(CONTINUE, 100) \
V(SWITCHING_PROTOCOLS, 101) \
V(PROCESSING, 102) \
V(EARLY_HINTS, 103) \
V(OK, 200) \
// ... ..。最后,在另一系列#define语句中连接到http2模块 constants支柱:
#define V(name, _) NODE_DEFINE_CONSTANT(constants, HTTP_STATUS_##name);
HTTP_STATUS_CODES(V)
#undef V有趣的是,Node中还有另一个存储相同数据的地方(状态代码是键,而不是值):它是http模块。来源
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
// ...https://stackoverflow.com/questions/68235792
复制相似问题