3

I'm trying to execute a Function object which is essentially the same as the following pseudo-code:

var testF = new Function("x","y", "var http = require('http');");
testF('foo','bar');

And get:

ReferenceError: require is not defined

Do I need to somehow add something that reloads the require module as it's not a global module in Node? If so, google has not been my friend so any pointers on how to do so would be fantastic.

Thanks for your ideas.

Scott Graph
  • 537
  • 5
  • 11

2 Answers2

8

Since new Function is a form of eval you can just eval it:

eval("function testF(x,y){ console.log(require);}");
testF(1,2);

If you want to follow the original approach you'll need to pass those globals to the function scope:

var testF = new Function(
  'exports',
  'require',
  'module',
  '__filename',
  '__dirname',
  "return function(x,y){console.log(x+y);console.log(require);}"
  )(exports,require,module,__filename,__dirname);

testF(1,2); 
Zachary Raineri
  • 148
  • 1
  • 12
Maroshii
  • 3,937
  • 4
  • 23
  • 29
  • I was hoping not to use eval and so I'm going to refactor using another technique to dynamically generate functions. Your very helpful answer helped to point me in another direction – Scott Graph Mar 25 '14 at 02:45
2

Another possible solution, using the same method of calling the Function constructor:

var testF = new Function("x","y", "var require = global.require || global.process.mainModule.constructor._load; var http = require('http');");
testF('foo','bar');
skypjack
  • 49,335
  • 19
  • 95
  • 187