javascript - Node.js 在另一个文件中运行文件
问题描述
这是我当前的代码
function includeClass(classname, ctx) {
var txt = fs.readFileSync("socket.io/" + classname + ".js");
return txt;
}
//define globals here
var _PLAYERS = {};
var _SPAWNPOINTS = [];
vm.runInThisContext(includeClass("vector"));
vm.runInThisContext(includeClass("class"));
vm.runInThisContext(includeClass("connectionHandler"));
vm.runInThisContext(includeClass("game"));
但是这样一来,class.js 文件就无法从全局范围或其他文件中访问变量。因为现在我得到了类似的错误,_PLAYERS
或者require
是未定义的。我也试过eval()
了,但它根本没有做任何事情。
如何在主脚本中运行这些 js 脚本,以便将它们解释为 1 个整体?
解决方案
https://nodejs.org/api/vm.html#vm_vm_runinthiscontext_code_options:
Running code does not have access to local scope, but does have access to the current global object.
Your _PLAYERS
variable is not truly global, it is local to your script. As well as some other variables (like require
) which are also in the module scope.
You can try to assign the needed variables to global
object, however, I am not well aware what side effects and complications may follow.
推荐阅读
- validation - 接口转换:interface {} 为 nil,不是 validator.ValidationErrors
- node.js - 路由器无法连接到 MongoDB 集群
- swift - 推送通知不会在 ios 中自动触发
- oracle - PL/SQL 函数 - 批量收集到管道行
- azure-devops - 如何在 Azure DevOps 上的发布管道中添加插槽交换任务之前的批准
- java - 过滤给定集合元素的增量条件
- ionic4 - 如何动态转到上一页(离子4)?
- javascript - 为什么为破坏变量未定义
- docker - 进程一直挂着
- typescript - 如何选择对象的字符串成员