为什么非交互式功能对象内的上下文在node.js中不同? [英] Why is context inside non-interactive Function object different in node.js?

查看:92
本文介绍了为什么非交互式功能对象内的上下文在node.js中不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从需要另一个模块的字符串创建函数(不要问).

I'd like to create a function from string that requires another module (don't ask).

当我尝试在节点交互式外壳中执行此操作时,一切都很好并且很花哨:

When I try to do that in node interactive shell, everything is fine and dandy:

> f = new Function("return require('crypto')");
[Function]
> f.call()
{ Credentials: [Function: Credentials],
  (...)
  prng: [Function] }

但是,当我在文件中放入完全相同的代码时,会被告知require函数不可用:

However, when I put the exact same code in file, I am told that require function is not avaliable:

israfel:apiary almad$ node test.coffee 

undefined:2
return require('crypto')
       ^
ReferenceError: require is not defined
    at eval at <anonymous> (/tmp/test.coffee:1:67)
    at Object.<anonymous> (/tmp/test.coffee:2:3)
    at Module._compile (module.js:446:26)
    at Object..js (module.js:464:10)
    at Module.load (module.js:353:31)
    at Function._load (module.js:311:12)
    at Array.0 (module.js:484:10)
    at EventEmitter._tickCallback (node.js:190:38)

该如何解决?

此外,它告诉我我对node.js上下文/作用域一无所知.那是什么?

Also, it tells me I do not know something about node.js contexts/scopes. What is that?

推荐答案

问题是范围.

正在全局范围内评估new Function()的参数.但是,节点仅将require定义为其交互模式/shell的全局变量.否则,它将在闭包中执行每个模块,其中requiremoduleexports等定义为局部变量.

The argument to new Function() is being evaluated in the global scope. Node, however, only defines require as a global for its interactive mode/shell. Otherwise, it executes each module within a closure where require, module, exports, etc. are defined as local variables.

因此,要定义函数以使require在范围内(关闭),则必须使用 function运算符/关键字:

So, to define the function so that require is in scope (closure), you'll have to use the function operator/keyword:

f = function () { return require('crypto'); }

或者,在CoffeeScript中, ->运算符:

Or, the -> operator in CoffeeScript:

f = -> require 'crypto'

这篇关于为什么非交互式功能对象内的上下文在node.js中不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆