0

this is my current code

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"));

But that way, class.js file can't access variables from global scope or other files. because now i get errors like, _PLAYERS or require is undefined. I've tried eval() too, but it didn't do anything at all.

How can I run these js scripts in main script so they get interpreted as 1 whole?

Nick
  • 455
  • 9
  • 28
  • Did you see this? https://stackoverflow.com/questions/3922994/share-variables-between-files-in-node-js – ttulka Jan 27 '19 at 17:15
  • @ttulka thats very ugly way of achieving overall goal, especially setting constants like __dirname and require or other functions. I can't believe there is no way of just binding two files into 1, its an interpreted language anyways! – Nick Jan 27 '19 at 17:38

1 Answers1

0

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.

vsemozhebuty
  • 12,992
  • 1
  • 26
  • 26