首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >确实需要in使用eval在另一个文件中运行代码。

问确实需要in使用eval在另一个文件中运行代码。
EN

Stack Overflow用户
提问于 2018-09-16 04:54:10
回答 2查看 1.4K关注 0票数 4

我只是想了解节点中的模块。我很少理解像节点这样的东西,它围绕放置在每个文件中的代码创建一个模块包装器函数。

假设有两个文件,a.js和b.js

在a.js中,当我第一次需要b.js时,如何执行b.js中存在的模块包装器函数。

节点是否执行类似的操作,以字符串形式获取b.js文件的全部内容,然后使用eval从a.js执行该内容,然后将此函数调用的结果保存在缓存中。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-09-16 05:14:00

或多或少。

Node.js 负载脚本文件内容和包扎与模块包装器

代码语言:javascript
复制
Module.wrap = function(script) {
  return Module.wrapper[0] + script + Module.wrapper[1];
};

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

然后模块函数为已评估和vm.runInThisContext。

代码语言:javascript
复制
  var wrapper = Module.wrap(content);

  var compiledWrapper = vm.runInThisContext(wrapper, {
    filename: filename,
    lineOffset: 0,
    displayErrors: true
  });

vm模块提供V8执行上下文,vm.runInThisContext计算代码的方式类似于间接eval

vm.runInThisContext()编译代码,在当前全局的上下文中运行它并返回结果。正在运行的代码不能访问本地范围,但可以访问当前的全局对象。 <...> 因为vm.runInThisContext()不能访问本地作用域,所以localVar保持不变。相反,eval()确实可以访问本地作用域,因此值localVar被更改。通过这种方式,vm.runInThisContext()非常类似于一个间接eval()调用,例如(0,eval)('code')。

票数 3
EN

Stack Overflow用户

发布于 2018-09-16 05:12:09

当您确实需要时,node.js有负责加载模块的loader.js文件。下面的步骤由loader.js文件执行

  1. 首先,它检查模块是否存在于缓存模块中。检查由Module._cache完成。
  2. 如果缓存中不存在,则创建一个新的Module实例。
  3. 保存到缓存中
  4. 用给定的文件名调用module.load()。这将在读取文件内容之后调用module.compile()。
  5. 如果解析文件时出错(因为在任何编译器进行编译时,都有词法分析和解析的步骤),则从缓存中删除该模块。
  6. 然后返回module.export对象。

我们知道节点是开源的,我直接给出了loader.js of node.js的github路径

loader.js路径

下面是Module._load函数的代码,由Node.js团队编写

代码语言:javascript
复制
// Check the cache for the requested file.
// 1. If a module already exists in the cache: return its exports object.
// 2. If the module is native: call `NativeModule.require()` with the
//    filename and return the result.
// 3. Otherwise, create a new module for the file and save it to the cache.
//    Then have it load  the file contents before returning its exports
//    object.
Module._load = function(request, parent, isMain) {
  if (parent) {
    debug('Module._load REQUEST %s parent: %s', request, parent.id);
  }

  var filename = Module._resolveFilename(request, parent, isMain);

  var cachedModule = Module._cache[filename];
  if (cachedModule) {
    updateChildren(parent, cachedModule, true);
    return cachedModule.exports;
  }

  if (NativeModule.nonInternalExists(filename)) {
    debug('load native module %s', request);
    return NativeModule.require(filename);
  }

  // Don't call updateChildren(), Module constructor already does.
  var module = new Module(filename, parent);

  if (isMain) {
    process.mainModule = module;
    module.id = '.';
  }

  Module._cache[filename] = module;

  tryModuleLoad(module, filename);

  return module.exports;
};

还请检查本文以了解流程如何工作。

实际工作

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52351057

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档