gpt4 book ai didi

javascript - Node 中是否需要使用 eval 来运行另一个文件中的代码

转载 作者:搜寻专家 更新时间:2023-10-31 23:44:41 24 4
gpt4 key购买 nike

我只是想了解 Node 中的模块。我了解一些事情,比如 Node 围绕每个文件中的代码创建了一个模块包装器函数。

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

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

node 是否做类似的事情,将 b.js 文件的全部内容作为字符串获取,然后使用 eval 从 a.js 执行它,然后将此函数调用的结果保存在缓存中。

最佳答案

或多或少。

Node.js loads脚本文件内容和wrapsmodule wrapper :

Module.wrap = function(script) {
return Module.wrapper[0] + script + Module.wrapper[1];
};

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

那么模块函数就是evaluated使用 vm.runInThisContext:

  var wrapper = Module.wrap(content);

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

vm 模块提供V8 execution context , 和 vm.runInThisContext计算代码类似于间接 eval:

vm.runInThisContext() compiles code, runs it within the context of the current global and returns the result. Running code does not have access to local scope, but does have access to the current global object.

<...>

Because vm.runInThisContext() does not have access to the local scope, localVar is unchanged. In contrast, eval() does have access to the local scope, so the value localVar is changed. In this way vm.runInThisContext() is much like an indirect eval() call, e.g. (0,eval)('code').

关于javascript - Node 中是否需要使用 eval 来运行另一个文件中的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52351057/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com