javascript - 为什么我能够将 require 的结果分配给一个对象?

标签 javascript node.js

我很好奇 require() 函数在 Node.js 中是如何工作的。

所以我正在研究 NodeJS 核心模块中的代码。

该文件在Webstorm中nodejs项目中的路径如下。

外部库\Node.js Core\core-modules\internal\modules\cjs\loader.js

const {   
       makeRequireFunction,   
       requireDepth,   
       stripBOM,   
       stripShebang } = require('internal/modules/cjs/helpers');

所以,我还没有在 javascript 中看到以上形式的变量。 我还发现数组中的文本是 helper.js 中的函数名称。

helper.js 路径如下。

外部库\Node.js Core\core-modules\internal\modules\cjs\helper.js

// Invoke with makeRequireFunction(module) where |module| is the Module 

object
// to use as the context for the require() function.
function makeRequireFunction(mod) {
  const Module = mod.constructor;

  function require(path) {
    try {
      exports.requireDepth += 1;
      return mod.require(path);
    } finally {
      exports.requireDepth -= 1;
    }
  }

  function resolve(request, options) {
    if (typeof request !== 'string') {
      throw new ERR_INVALID_ARG_TYPE('request', 'string', request);
    }
    return Module._resolveFilename(request, mod, false, options);
  }

  require.resolve = resolve;

  function paths(request) {
    if (typeof request !== 'string') {
      throw new ERR_INVALID_ARG_TYPE('request', 'string', request);
    }
    return Module._resolveLookupPaths(request, mod, true);
  }

  resolve.paths = paths;

  require.main = process.mainModule;

  // Enable support to add extra extension types.
  require.extensions = Module._extensions;

  require.cache = Module._cache;

  return require;
}

我什至想不出这个变量是如何工作的。

最佳答案

这叫做 Object Destructuring . require 返回一个包含多个键(包括您示例中的键)的对象,ES6+ javascript 将使每个键都可用作直接常量

例子:

// object containing name, country & job keys
const person = {name: "John Doe", country: "Belgium", job: "Developer"};

// destructuring assignment, grabbing name, country & job from the person object
const {name, country, job} = person;

console.log(name);//"John Doe"
console.log(country);//"Belgium"
console.log(job);//"Developer"

请注意,您还可以使用类似的语法分配不同的变量名称。
给定上一个对象:

const {job: occupation} = person

console.log(occupation); //"Developer"
Node 中的

require 解析 JavaScript 文件并返回一个 window.exports 对象,该对象是通过在原始 JS 周围包装一些代码而创建的。参见 What does require() actually return, the file or the functionhttps://nodejs.org/api/modules.html#modules_require_id

额外资源:MDN resource

关于javascript - 为什么我能够将 require 的结果分配给一个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54254740/

相关文章:

node.js - 如何在 Node js中定义属性文件?

node.js - 如何让 Google API 返回 node.js 上两点之间的距离并将其存储在变量中?

node.js - 从 Angular 2 发送电子邮件

php - 执行 Javascript 服务器端

javascript - dxTooltip 无法在 IE 中工作,但在 Chrome 中工作

java - 如何在jsp中从我自己的应用程序播放视频文件(文件位于我自己的服务器Mysql数据库中。)

javascript - Jade 中的过滤器嵌套失败

javascript - 如何通过封装实现验证

javascript - Ember Js 中应用程序的全局 Controller

node.js - 处理WebRTC byte []流?