探索 Node.js 源码,详解cjs 模块的加载过程

探索 Node.js 源码,详解cjs 模块的加载过程

相信大家都知道如何在 Node 中加载一个模块:

const fs = require('fs');const express = require('express');const anotherModule = require('./another-module');

没错,require 就是加载 cjs 模块的 API,但 V8 本身是没有 cjs 模块系统的,所以 node 是怎么通过 require找到模块并且加载的呢?【相关教程推荐:nodejs视频教程】      

我们今天将对 Node.js 源码进行探索,深入理解 cjs 模块的加载过程。我们阅读的 node 代码版本为 v17.x:

git head :881174e016d6c27b20c70111e6eae2296b6c6293代码链接:github.com/nodejs/node…

源码阅读

内置模块

为了知道 require 的工作逻辑,我们需要先了解内置模块是如何被加载到 node 中的(诸如 ‘fs’,’path’,’child_process’,其中也包括一些无法被用户引用的内部模块),准备好代码之后,我们首先要从 node 启动开始阅读。node 的 main 函数在 [src/node_main.cc](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/src/node_main.cc#L105) 内,通过调用方法 [node::Start](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/src/node.cc#L1134) 来启动一个 node 实例:

int Start(int argc, char** argv) {  InitializationResult result = InitializeOncePerProcess(argc, argv);  if (result.early_return) {    return result.exit_code;  }  {    Isolate::CreateParams params;    const std::vector* indices = nullptr;    const EnvSerializeInfo* env_info = nullptr;    bool use_node_snapshot =        per_process::cli_options->per_isolate->node_snapshot;    if (use_node_snapshot) {      v8::StartupData* blob = NodeMainInstance::GetEmbeddedSnapshotBlob();      if (blob != nullptr) {        params.snapshot_blob = blob;        indices = NodeMainInstance::GetIsolateDataIndices();        env_info = NodeMainInstance::GetEnvSerializeInfo();      }    }    uv_loop_configure(uv_default_loop(), UV_METRICS_IDLE_TIME);    NodeMainInstance main_instance(&params,                                   uv_default_loop(),                                   per_process::v8_platform.Platform(),                                   result.args,                                   result.exec_args,                                   indices);    result.exit_code = main_instance.Run(env_info);  }  TearDownOncePerProcess();  return result.exit_code;}

这里创建了事件循环,且创建了一个 NodeMainInstance 的实例 main_instance 并调用了它的 Run 方法:

int NodeMainInstance::Run(const EnvSerializeInfo* env_info) {  Locker locker(isolate_);  Isolate::Scope isolate_scope(isolate_);  HandleScope handle_scope(isolate_);  int exit_code = 0;  DeleteFnPtr env =      CreateMainEnvironment(&exit_code, env_info);  CHECK_NOT_NULL(env);  Context::Scope context_scope(env->context());  Run(&exit_code, env.get());  return exit_code;}

Run 方法中调用 [CreateMainEnvironment](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/src/node_main_instance.cc#L170) 来创建并初始化环境:

Environment* CreateEnvironment(    IsolateData* isolate_data,    Local context,    const std::vector& args,    const std::vector& exec_args,    EnvironmentFlags::Flags flags,    ThreadId thread_id,    std::unique_ptr inspector_parent_handle) {  Isolate* isolate = context->GetIsolate();  HandleScope handle_scope(isolate);  Context::Scope context_scope(context);  // TODO(addaleax): This is a much better place for parsing per-Environment  // options than the global parse call.  Environment* env = new Environment(      isolate_data, context, args, exec_args, nullptr, flags, thread_id);#if HAVE_INSPECTOR  if (inspector_parent_handle) {    env->InitializeInspector(        std::move(static_cast(            inspector_parent_handle.get())->impl));  } else {    env->InitializeInspector({});  }#endif  if (env->RunBootstrapping().IsEmpty()) {    FreeEnvironment(env);    return nullptr;  }  return env;}

创建 Environment 对象 env 并调用其 [RunBootstrapping](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/src/node.cc#L398) 方法:

MaybeLocal Environment::RunBootstrapping() {  EscapableHandleScope scope(isolate_);  CHECK(!has_run_bootstrapping_code());  if (BootstrapInternalLoaders().IsEmpty()) {    return MaybeLocal();  }  Local result;  if (!BootstrapNode().ToLocal(&result)) {    return MaybeLocal();  }  // Make sure that no request or handle is created during bootstrap -  // if necessary those should be done in pre-execution.  // Usually, doing so would trigger the checks present in the ReqWrap and  // HandleWrap classes, so this is only a consistency check.  CHECK(req_wrap_queue()->IsEmpty());  CHECK(handle_wrap_queue()->IsEmpty());  DoneBootstrapping();  return scope.Escape(result);}

这里的 [BootstrapInternalLoaders](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/src/node.cc#L298) 实现了 node 模块加载过程中非常重要的一步:通过包装并执行 [internal/bootstrap/loaders.js](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/lib/internal/bootstrap/loaders.js#L326) 获取内置模块的 [nativeModulerequire](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/lib/internal/bootstrap/loaders.js#L332) 函数用于加载内置的 js 模块,获取 [internalBinding](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/lib/internal/bootstrap/loaders.js#L164) 用于加载内置的 C++ 模块,[NativeModule](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/lib/internal/bootstrap/loaders.js#L191) 则是专门用于内置模块的小型模块系统。

function nativeModuleRequire(id) {  if (id === loaderId) {    return loaderExports;  }  const mod = NativeModule.map.get(id);  // Can't load the internal errors module from here, have to use a raw error.  // eslint-disable-next-line no-restricted-syntax  if (!mod) throw new TypeError(`Missing internal module '${id}'`);  return mod.compileForInternalLoader();}const loaderExports = {  internalBinding,  NativeModule,  require: nativeModuleRequire};return loaderExports;

需要注意的是,这个 require 函数只会被用于内置模块的加载,用户模块的加载并不会用到它。(这也是为什么我们通过打印 require('module')._cache 可以看到所有用户模块,却看不到 fs 等内置模块的原因,因为两者的加载和缓存维护方式并不一样)。

用户模块

接下来让我们把目光移回到 [NodeMainInstance::Run](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/src/node_main_instance.cc#L127) 函数:

int NodeMainInstance::Run(const EnvSerializeInfo* env_info) {  Locker locker(isolate_);  Isolate::Scope isolate_scope(isolate_);  HandleScope handle_scope(isolate_);  int exit_code = 0;  DeleteFnPtr env =      CreateMainEnvironment(&exit_code, env_info);  CHECK_NOT_NULL(env);  Context::Scope context_scope(env->context());  Run(&exit_code, env.get());  return exit_code;}

我们已经通过 CreateMainEnvironment 函数创建好了一个 env 对象,这个 Environment 实例已经有了一个模块系统 NativeModule 用于维护内置模块。然后代码会运行到 Run 函数的另一个重载版本:

void NodeMainInstance::Run(int* exit_code, Environment* env) {  if (*exit_code == 0) {    LoadEnvironment(env, StartExecutionCallback{});    *exit_code = SpinEventLoop(env).FromMaybe(1);  }  ResetStdio();  // TODO(addaleax): Neither NODE_SHARED_MODE nor HAVE_INSPECTOR really  // make sense here.#if HAVE_INSPECTOR && defined(__POSIX__) && !defined(NODE_SHARED_MODE)  struct sigaction act;  memset(&act, 0, sizeof(act));  for (unsigned nr = 1; nr < kMaxSignal; nr += 1) {    if (nr == SIGKILL || nr == SIGSTOP || nr == SIGPROF)      continue;    act.sa_handler = (nr == SIGPIPE) ? SIG_IGN : SIG_DFL;    CHECK_EQ(0, sigaction(nr, &act, nullptr));  }#endif#if defined(LEAK_SANITIZER)  __lsan_do_leak_check();#endif}

在这里调用 [LoadEnvironment](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/src/api/environment.cc#L403)

MaybeLocal LoadEnvironment(    Environment* env,    StartExecutionCallback cb) {  env->InitializeLibuv();  env->InitializeDiagnostics();  return StartExecution(env, cb);}

然后执行 [StartExecution](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/src/node.cc#L455)

MaybeLocal StartExecution(Environment* env, StartExecutionCallback cb) {  // 已省略其他运行方式,我们只看 `node index.js` 这种情况,不影响我们理解模块系统  if (!first_argv.empty() && first_argv != "-") {    return StartExecution(env, "internal/main/run_main_module");  }}

StartExecution(env, "internal/main/run_main_module")这个调用中,我们会包装一个 function,并传入刚刚从 loaders 中导出的 require 函数,并运行 [lib/internal/main/run_main_module.js](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/lib/internal/main/run_main_module.js) 内的代码:

'use strict';const {  prepareMainThreadExecution} = require('internal/bootstrap/pre_execution');prepareMainThreadExecution(true);markBootstrapComplete();// Note: this loads the module through the ESM loader if the module is// determined to be an ES module. This hangs from the CJS module loader// because we currently allow monkey-patching of the module loaders// in the preloaded scripts through require('module').// runMain here might be monkey-patched by users in --require.// XXX: the monkey-patchability here should probably be deprecated.require('internal/modules/cjs/loader').Module.runMain(process.argv[1]);

所谓的包装 function 并传入 require,伪代码如下:

(function(require, /* 其他入参 */) {  // 这里是 internal/main/run_main_module.js 的文件内容})();

所以这里是通过内置模块require 函数加载了 [lib/internal/modules/cjs/loader.js](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/lib/internal/modules/cjs/loader.js#L172) 导出的 Module 对象上的 runMain 方法,不过我们在 loader.js 中并没有发现 runMain 函数,其实这个函数是在 [lib/internal/bootstrap/pre_execution.js](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/lib/internal/bootstrap/pre_execution.js#L428) 中被定义到 Module 对象上的:

Imagine By Magic Studio Imagine By Magic Studio

AI图片生成器,用文字制作图片

Imagine By Magic Studio 79 查看详情 Imagine By Magic Studio

function initializeCJSLoader() {  const CJSLoader = require('internal/modules/cjs/loader');  if (!noGlobalSearchPaths) {    CJSLoader.Module._initPaths();  }  // TODO(joyeecheung): deprecate this in favor of a proper hook?  CJSLoader.Module.runMain =    require('internal/modules/run_main').executeUserEntryPoint;}

[lib/internal/modules/run_main.js](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/lib/internal/modules/run_main.js#L74) 中找到 executeUserEntryPoint 方法:

function executeUserEntryPoint(main = process.argv[1]) {  const resolvedMain = resolveMainPath(main);  const useESMLoader = shouldUseESMLoader(resolvedMain);  if (useESMLoader) {    runMainESM(resolvedMain || main);  } else {    // Module._load is the monkey-patchable CJS module loader.    Module._load(main, null, true);  }}

参数 main 即为我们传入的入口文件 index.js。可以看到,index.js 作为一个 cjs 模块应该被 Module._load 加载,那么 _load干了些什么呢?这个函数是 cjs 模块加载过程中最重要的一个函数,值得仔细阅读:

// `_load` 函数检查请求文件的缓存// 1. 如果模块已经存在,返回已缓存的 exports 对象// 2. 如果模块是内置模块,通过调用 `NativeModule.prototype.compileForPublicLoader()`//    获取内置模块的 exports 对象,compileForPublicLoader 函数是有白名单的,只能获取公开//    内置模块的 exports。// 3. 以上两者皆为否,创建新的 Module 对象并保存到缓存中,然后通过它加载文件并返回其 exports。// request:请求的模块,比如 `fs`,`./another-module`,'@pipcook/core' 等// parent:父模块,如在 `a.js` 中 `require('b.js')`,那么这里的 request 为 'b.js',           parent 为 `a.js` 对应的 Module 对象// isMain: 除入口文件为 `true` 外,其他模块都为 `false`Module._load = function(request, parent, isMain) {  let relResolveCacheIdentifier;  if (parent) {    debug('Module._load REQUEST %s parent: %s', request, parent.id);    // relativeResolveCache 是模块路径缓存,    // 用于加速父模块所在目录下的所有模块请求当前模块时    // 可以直接查询到实际路径,而不需要通过 _resolveFilename 查找文件    relResolveCacheIdentifier = `${parent.path}x00${request}`;    const filename = relativeResolveCache[relResolveCacheIdentifier];    if (filename !== undefined) {      const cachedModule = Module._cache[filename];      if (cachedModule !== undefined) {        updateChildren(parent, cachedModule, true);        if (!cachedModule.loaded)          return getExportsForCircularRequire(cachedModule);        return cachedModule.exports;      }      delete relativeResolveCache[relResolveCacheIdentifier];    }  }// 尝试查找模块文件路径,找不到模块抛出异常  const filename = Module._resolveFilename(request, parent, isMain);  // 如果是内置模块,从 `NativeModule` 加载  if (StringPrototypeStartsWith(filename, 'node:')) {    // Slice 'node:' prefix    const id = StringPrototypeSlice(filename, 5);    const module = loadNativeModule(id, request);    if (!module?.canBeRequiredByUsers) {      throw new ERR_UNKNOWN_BUILTIN_MODULE(filename);    }    return module.exports;  }// 如果缓存中已存在,将当前模块 push 到父模块的 children 字段  const cachedModule = Module._cache[filename];  if (cachedModule !== undefined) {    updateChildren(parent, cachedModule, true);    // 处理循环引用    if (!cachedModule.loaded) {      const parseCachedModule = cjsParseCache.get(cachedModule);      if (!parseCachedModule || parseCachedModule.loaded)        return getExportsForCircularRequire(cachedModule);      parseCachedModule.loaded = true;    } else {      return cachedModule.exports;    }  }// 尝试从内置模块加载  const mod = loadNativeModule(filename, request);  if (mod?.canBeRequiredByUsers) return mod.exports;  // Don't call updateChildren(), Module constructor already does.  const module = cachedModule || new Module(filename, parent);  if (isMain) {    process.mainModule = module;    module.id = '.';  }// 将 module 对象加入缓存  Module._cache[filename] = module;  if (parent !== undefined) {    relativeResolveCache[relResolveCacheIdentifier] = filename;  }  // 尝试加载模块,如果加载失败则删除缓存中的 module 对象,  // 同时删除父模块的 children 内的 module 对象。  let threw = true;  try {    module.load(filename);    threw = false;  } finally {    if (threw) {      delete Module._cache[filename];      if (parent !== undefined) {        delete relativeResolveCache[relResolveCacheIdentifier];        const children = parent?.children;        if (ArrayIsArray(children)) {          const index = ArrayPrototypeIndexOf(children, module);          if (index !== -1) {            ArrayPrototypeSplice(children, index, 1);          }        }      }    } else if (module.exports &&               !isProxy(module.exports) &&               ObjectGetPrototypeOf(module.exports) ===                 CircularRequirePrototypeWarningProxy) {      ObjectSetPrototypeOf(module.exports, ObjectPrototype);    }  }// 返回 exports 对象  return module.exports;};

module 对象上的 [load](https://github.com/nodejs/node/blob/881174e016d6c27b20c70111e6eae2296b6c6293/lib/internal/modules/cjs/loader.js#L963) 函数用于执行一个模块的加载:

Module.prototype.load = function(filename) {  debug('load %j for module %j', filename, this.id);  assert(!this.loaded);  this.filename = filename;  this.paths = Module._nodeModulePaths(path.dirname(filename));  const extension = findLongestRegisteredExtension(filename);  // allow .mjs to be overridden  if (StringPrototypeEndsWith(filename, '.mjs') && !Module._extensions['.mjs'])    throw new ERR_REQUIRE_ESM(filename, true);  Module._extensions[extension](this, filename);  this.loaded = true;  const esmLoader = asyncESM.esmLoader;  // Create module entry at load time to snapshot exports correctly  const exports = this.exports;  // Preemptively cache  if ((module?.module === undefined ||       module.module.getStatus() < kEvaluated) &&      !esmLoader.cjsCache.has(this))    esmLoader.cjsCache.set(this, exports);};

实际的加载动作是在 Module._extensions[extension](this, filename); 中进行的,根据扩展名的不同,会有不同的加载策略:

.js:调用 fs.readFileSync 读取文件内容,将文件内容包在 wrapper 中,需要注意的是,这里的 requireModule.prototype.require 而非内置模块的 require 方法。

const wrapper = [  '(function (exports, require, module, __filename, __dirname) { ',  'n});',];

.json:调用 fs.readFileSync 读取文件内容,并转换为对象。.node:调用 dlopen 打开 node 扩展。

Module.prototype.require 函数也是调用了静态方法 Module._load实现模块加载的:

Module.prototype.require = function(id) {  validateString(id, 'id');  if (id === '') {    throw new ERR_INVALID_ARG_VALUE('id', id,                                    'must be a non-empty string');  }  requireDepth++;  try {    return Module._load(id, this, /* isMain */ false);  } finally {    requireDepth--;  }};

总结

看到这里,cjs 模块的加载过程已经基本清晰了:

初始化 node,加载 NativeModule,用于加载所有的内置的 js 和 c++ 模块

运行内置模块 run_main

run_main 中引入用户模块系统 module

通过 module_load 方法加载入口文件,在加载时通过传入 module.requiremodule.exports 等让入口文件可以正常 require 其他依赖模块并递归让整个依赖树被完整加载。

在清楚了 cjs 模块加载的完整流程之后,我们还可以顺着这条链路阅读其他代码,比如 global 变量的初始化,esModule 的管理方式等,更深入地理解 node 内的各种实现。

更多node相关知识,请访问:nodejs 教程!

以上就是探索 Node.js 源码,详解cjs 模块的加载过程的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/834994.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
超自然行动组精绝古城困难┳型全地图小抄
上一篇 2025年11月27日 10:01:42
Linux清理秘籍:释放磁盘空间的方法
下一篇 2025年11月27日 10:01:44

相关推荐

  • 修复Django电商项目中AJAX过滤产品列表图片不显示问题

    在Django电商项目中,当使用AJAX动态加载过滤后的产品列表时,常遇到图片无法正常显示的问题。这通常是由于前端模板中图片加载方式(如data-setbg属性结合JavaScript库)与AJAX动态内容更新机制不兼容所致。解决方案是直接在AJAX返回的HTML中使用标准的标签来渲染图片,确保浏览…

    2026年5月10日
    000
  • 开源免费PHP工具 PHP开发效率提升利器

    推荐开源免费PHP开发工具以提升效率:VS Code、Sublime Text轻量高效,PhpStorm专业强大;调试用Xdebug、Kint、Ray;依赖管理选Composer;代码质量工具包括PHPStan、Psalm、PHP_CodeSniffer;数据库管理可用%ignore_a_1%MyA…

    2026年5月10日
    000
  • Matplotlib 地图中多类型图例的创建与优化

    Matplotlib 地图中多类型图例的创建与优化Matplotlib 地图中多类型图例的创建与优化Matplotlib 地图中多类型图例的创建与优化Matplotlib 地图中多类型图例的创建与优化

    本教程旨在解决matplotlib地图可视化中,如何在一个图例中同时展示颜色块(如区域分类)和自定义标记(如特定兴趣点)的问题。文章详细介绍了当传统`patch`对象无法正确显示标记时,如何利用`matplotlib.lines.line2d`创建标记图例句柄,并将其与颜色块图例句柄合并,从而生成一…

    2026年5月10日 用户投稿
    100
  • Golang JSON序列化:控制敏感字段暴露的最佳实践

    本教程探讨golang中如何高效控制结构体字段在json序列化时的可见性。当需要将包含敏感信息的结构体数组转换为json响应时,通过利用`encoding/json`包提供的结构体标签,特别是`json:”-“`,可以轻松实现对特定字段的忽略,从而避免敏感数据泄露,确保api…

    2026年5月10日
    000
  • 比特币新手教程 比特币交易平台有哪些

    比特币是一种去中心化的数字货币,基于区块链技术实现点对点交易,具有匿名性、有限发行和不可篡改等特点;新手可通过交易所购买,P2P交易获得比特币,常用平台包括Binance、OKX和Huobi;交易流程包括注册账户、实名认证、绑定支付方式、充值法币并下单购买,可选择市价单或限价单;比特币存储方式有交易…

    2026年5月10日
    000
  • c++中的SFINAE技术是什么_c++模板编程中的SFINAE原理与应用

    SFINAE 是“替换失败不是错误”的原则,指模板实例化时若参数替换导致错误,只要存在其他合法候选,编译器不报错而是继续重载决议。它用于条件启用模板、类型检测等场景,如通过 decltype 或 enable_if 控制函数重载,实现类型特征判断。尽管 C++20 引入 Concepts 简化了部分…

    2026年5月10日
    000
  • Go语言mgo查询构建:深入理解bson.M与日期范围查询的正确实践

    本文旨在解决go语言mgo库中构建复杂查询时,特别是涉及嵌套`bson.m`和日期范围筛选的常见错误。我们将深入剖析`bson.m`的类型特性,解释为何直接索引`interface{}`会导致“invalid operation”错误,并提供一种推荐的、结构清晰的代码重构方案,以确保查询条件能够正确…

    2026年5月10日
    100
  • RichHandler与Rich Progress集成:解决显示冲突的教程

    在使用rich库的`richhandler`进行日志输出并同时使用`progress`组件时,可能会遇到显示错乱或溢出问题。这通常是由于为`richhandler`和`progress`分别创建了独立的`console`实例导致的。解决方案是确保日志处理器和进度条组件共享同一个`console`实例…

    2026年5月10日
    000
  • Golang goroutine与channel调试技巧

    使用go run -race检测数据竞争,结合runtime.NumGoroutine监控协程数量,通过pprof分析阻塞调用栈,利用select超时避免永久阻塞,有效排查goroutine泄漏、死锁和数据竞争问题。 Go语言的goroutine和channel是并发编程的核心,但它们也带来了调试上…

    2026年5月10日
    000
  • 使用 Jupyter Notebook 进行探索性数据分析

    Jupyter Notebook通过单元格实现代码与Markdown结合,支持数据导入(pandas)、清洗(fillna)、探索(matplotlib/seaborn可视化)、统计分析(describe/corr)和特征工程,便于记录与分享分析过程。 Jupyter Notebook 是进行探索性…

    2026年5月10日
    000
  • 《魔兽世界》将于6月11日开启国服回归技术测试

    《魔兽世界》将于6月11日开启国服回归技术测试《魔兽世界》将于6月11日开启国服回归技术测试《魔兽世界》将于6月11日开启国服回归技术测试《魔兽世界》将于6月11日开启国服回归技术测试

    《%ign%ignore_a_1%re_a_1%》官方宣布,将于6月11日开启国服回归技术测试,时间为7天,并称可以在6月内正式开服,玩家们可以访问官网下载战网客户端并预下载“巫妖王之怒”客户端,技术测试详情见下图。 WordAi WordAI是一个AI驱动的内容重写平台 53 查看详情 以上就是《…

    2026年5月10日 用户投稿
    200
  • 如何在HTML中插入表单元素_HTML表单控件与输入类型使用指南

    HTML表单通过标签构建,包含action和method属性定义数据提交目标与方式,常用input类型如text、password、email等适配不同输入需求,配合label、required、placeholder提升可用性,结合textarea、select、button等控件实现完整交互,是…

    2026年5月10日
    000
  • 前端缓存策略与JavaScript存储管理

    根据数据特性选择合适的存储方式并制定清晰的读写与清理逻辑,能显著提升前端性能;合理运用Cookie、localStorage、sessionStorage、IndexedDB及Cache API,结合缓存策略与定期清理机制,可在保证用户体验的同时避免安全与性能隐患。 前端缓存和JavaScript存…

    2026年5月10日
    100
  • HTML5网页如何实现手势操作 HTML5网页移动端交互的处理技巧

    首先利用原生touch事件实现滑动判断,再通过preventDefault解决滚动冲突,接着引入Hammer.js处理复杂手势,最后通过优化点击区域、避免事件冲突和增加视觉反馈提升体验。 在移动端浏览器中,HTML5网页可以通过触摸事件实现手势操作,提升用户体验。虽然原生JavaScript提供了基…

    2026年5月10日
    000
  • 创建指定大小并填充特定数据的Golang文件教程

    本文将介绍如何使用Golang创建一个指定大小的文件,并用特定数据填充它。我们将使用 `os` 包提供的函数来创建和截断文件,从而实现快速生成大文件的目的。示例代码展示了如何创建一个10MB的文件,并将其填充为全零数据。掌握这些方法,可以方便地在例如日志系统或磁盘队列等场景中,预先创建测试文件或初始…

    2026年5月10日
    000
  • 深入理解 Express.js 中 next() 参数的作用与中间件机制

    本文深入探讨 express.js 中间件函数中的 `next()` 参数。它负责将控制权传递给请求-响应周期中的下一个中间件或路由处理程序。文章将详细解释 `next()` 的工作原理、中间件的注册与执行顺序,以及不正确使用 `next()` 可能导致请求挂起的风险,并通过代码示例和实际应用场景,…

    2026年5月10日
    000
  • Python命令怎样使用profile分析脚本性能 Python命令性能分析的基础教程

    使用Python的cProfile模块分析脚本性能最直接的方式是通过命令行执行python -m cProfile your_script.py,它会输出每个函数的调用次数、总耗时、累积耗时等关键指标,帮助定位性能瓶颈;为进一步分析,可将结果保存为文件python -m cProfile -o ou…

    2026年5月10日
    000
  • 使用 WebCodecs VideoDecoder 实现精确逐帧回退

    本文档旨在解决在使用 WebCodecs VideoDecoder 进行视频解码时,实现精确逐帧回退的问题。通过比较帧的时间戳与目标帧的时间戳,可以避免渲染中间帧,从而提高用户体验。本文将提供详细的解决方案和示例代码,帮助开发者实现精确的视频帧控制。 在使用 WebCodecs VideoDecod…

    2026年5月10日
    000
  • 如何插入查询结果数据_SQL插入Select查询结果方法

    如何插入查询结果数据_SQL插入Select查询结果方法如何插入查询结果数据_SQL插入Select查询结果方法如何插入查询结果数据_SQL插入Select查询结果方法如何插入查询结果数据_SQL插入Select查询结果方法

    使用INSERT INTO…SELECT语句可高效插入数据,通过NOT EXISTS、LEFT JOIN、MERGE语句或唯一约束避免重复;表结构不一致时可通过别名、类型转换、默认值或计算字段处理;结合存储过程可提升可维护性,支持参数化与动态SQL。 将查询结果数据插入到另一个表中,可以…

    2026年5月10日 用户投稿
    000
  • Discord.py 交互按钮超时与持久化解决方案

    本教程旨在解决Discord.py中交互按钮在一段时间后出现“This Interaction Failed”错误的问题。我们将深入探讨视图(View)的超时机制,并提供通过正确设置timeout参数以及利用bot.add_view()方法实现按钮持久化的具体方案,确保您的机器人交互功能稳定可靠,即…

    2026年5月10日
    000

发表回复

登录后才能评论
关注微信