user603749
user603749

Reputation: 1763

Access local variables context of nodejs main from included eval script

I have found the following way to include nodejs files rather handy without converting them to modules. There is only one small caveat. I would prefer not have to change my var to global in main.js so it can be accessible by the included.js file. As you can see in the included file I do not have to do that. And the variables there are accessible my main. See code. Is there someway that the local context of the main file of node can be accessed in the included file withouting having to resort to changing all var.* to global.* if I want them access by the include.

Here is the code

//Main file

//evalmain.js
var vm = require('vm');
var fs=require("fs");

global.globalVar = 0;  //<<-- *** Prefer var globalVar***

// Include the script 
var script = new vm.Script(fs.readFileSync(__dirname+"\\evalinc.js"+""));
script.runInThisContext();

console.log("globalVar: ", globalVar, "  evalVar: ", evalVar);
showvars();
console.log("globalVar: ",++globalVar, "  evalVar: ", evalVar);
evalVar="Now set in evalmain";
showvars();

//Include file

// evalinc.js is the file to be included
// Note, it's not a module. Just plain JS
debugger;
globalVar=100; // Sets the global variable at main!
var evalVar="Set in evalinc!";
var showvars=function(){
    console.log("globalVar: ",++globalVar, "  evalVar: ", evalVar);
}

Upvotes: 2

Views: 1353

Answers (2)

Bergi
Bergi

Reputation: 665040

Did you try a simple eval? I guess it does exactly the magic that you are expecting here, even without affecting the global scope.

var fs=require("fs");

var globalVar = 0;

eval(fs.readFileSync(__dirname+"\\evalinc.js")); // Include the script 

console.log("globalVar: ", globalVar, "  evalVar: ", evalVar);
showvars();
console.log("globalVar: ", ++globalVar, "  evalVar: ", evalVar);
evalVar = "Now set in evalmain";
showvars();

Upvotes: 1

Bergi
Bergi

Reputation: 665040

No, the local variable context is not programmatically accessible. You can however create a dedicated object that will become the context for the script:

var vm = require('vm');
var fs=require("fs");

var globals = {
    globalVar: 0
}; // not a global variable

// Include the script 
var script = new vm.Script(fs.readFileSync(__dirname+"\\evalinc.js"+""));
script.runInNewContext(globals);

console.log("globalVar: ", globals.globalVar, "  evalVar: ", globals.evalVar);
globals.showvars();
console.log("globalVar: ", ++globals.globalVar, "  evalVar: ", globals.evalVar);
globals.evalVar="Now set in evalmain";
globals.showvars();

Upvotes: 1

Related Questions