为什么我可以将require的结果分配给一个对象?

时间:2019-01-18 13:11:49

标签: javascript node.js

我很好奇Node.js中require()函数的工作原理。

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

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

External Libraries \ 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核心\核心模块\内部\模块\ 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;
}

我什至不认为该变量如何工作。

2 个答案:

答案 0 :(得分:7)

这叫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

答案 1 :(得分:1)

这称为Object Destructuring,通过对返回值(对象或数组)进行“匹配”来分配值。