Friday, 21 April 2017

Eval code in node's global scope from within a module

General: In node.js, how does one access the scope of the file being executed?

Example: I have a module (mod.js) and a file that requires it (main.js). From within mod.js I need to do an eval() with access to the scope of main.js, as follows:

mod.js:

exports.runCode = function(code) {
  return eval(code);
}

main.js:

var amod = require('./mod');

var func = function(a,b) {
  return a + b;
}

console.log(amod.runCode('2+2'));    // works fine
console.log(amod.runCode('func()')); // ReferenceError: func is not defined

bash:

$ node main


Thus far, I have tried using node's global, vm, and process objects, as well as various closures (and I am aware of the various security issues).



via rednoyz

No comments:

Post a Comment