我很好奇 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 function和 https://nodejs.org/api/modules.html#modules_require_id
额外资源:MDN resource
关于javascript - 为什么我能够将 require 的结果分配给一个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54254740/