首页 > 解决方案 > 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 个整体?

标签: javascriptnode.jseval

解决方案


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.


推荐阅读