【问题标题】:Use of internal Node.js module vs. public npm-module使用内部 Node.js 模块与公共 npm-module
【发布时间】:2021-09-15 00:49:07
【问题描述】:

为了保持代码简洁,我想避免使用硬编码值,而是使用预定义的常量,例如 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 使用了?

【问题讨论】:

    标签: node.js


    【解决方案1】:

    所有内部模块(包括http2)都是在Node启动时注册的。引用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)
    

    所以是的,我宁愿在你的情况下使用那个模块。


    顺便说一下,从技术上讲,HTTP 状态码甚至不是 http2 模块的一部分:它们作为一组宏存储在 node_http_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 module constants 道具:

    #define V(name, _) NODE_DEFINE_CONSTANT(constants, HTTP_STATUS_##name);
      HTTP_STATUS_CODES(V)
    #undef V
    

    有趣的是,Node 中还有另一个地方存储了相同的数据(状态码是键,而不是值):它是 http moduleSource:

    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
      // ...
    

    【讨论】:

    • 关于«在节点存储中还有另一个地方»,是的,我也注意到了,但是由于我想将此模块用作枚举,http2/constants 似乎是更合适的选择。
    • 您是否知道,Node.js 中是否存在针对httpsx-forwarded-proto 值的硬编码常量以避免硬编码?
    • 不,我不知道这些事情。即使有,节点本身doesn't use it
    猜你喜欢
    • 2023-03-04
    • 2010-10-17
    • 1970-01-01
    • 2021-06-14
    • 1970-01-01
    • 2016-04-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多