Node.JS使用Require()向CreateContext()添加访问节点模块

时间:2013-06-01 19:33:08

标签: javascript node.js sandbox child-process

在我的应用程序中,我创建了CreateContext,然后是RunInContext。我只需要在Context中添加对某些Node模块的访问权限。我知道如何添加自己的Javascript方法,但在添加async和http等Node模块时会出错。我怎么能这样做?

我正在使用Sandbox模块https://github.com/gf3/sandbox来运行子进程

代码

var context = Script.createContext();
    context.myOwnFunctions = function() {
//my own javascript
}
context.myNodeFunctions = function() {
//require('async')
//require('http')
/Add some function that use the items I required above
}
var run = Script.runInContext('code to run', context);

1 个答案:

答案 0 :(得分:1)

require返回模块,因此如果您不将其分配给某些内容,则该模块将无法使用。

var context = Script.createContext();
    context.myOwnFunctions = function() {
    //my own javascript
}
context.myNodeFunctions = function() {
    this.async = require('async');
    this.http = require('http');
    //Add some function that use the items I required above
}

var run = Script.runInContext('code to run', context);