Node" ReferenceError:require未定义"执行Function对象时

时间:2014-03-22 01:16:25

标签: node.js function require

我试图执行一个与以下伪代码基本相同的Function对象:

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

得到:

ReferenceError: require is not defined

我是否需要以某种方式添加重新加载require模块的内容,因为它不是Node中的全局模块?如果是这样,谷歌不是我的朋友,所以任何关于如何做的指针都会很棒。

感谢您的想法。

2 个答案:

答案 0 :(得分:3)

new Function is a form of eval起,你可以eval

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

如果您想要遵循原始方法,则需要将全局传递给函数范围:

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

答案 1 :(得分:0)

另一种可能的解决方案,使用调用Function构造函数的相同方法:

from   { transform: translate(0, 0); }
to { transform: translate(-100%, 0); } /* Instead of 100% */