2013-06-01 65 views
2

在我的應用程序中,我CreateContext,然後RunInContext。我需要添加對上下文中的某些節點模塊的訪問。我知道如何添加我自己的Javascript方法,但在添加像async和http這樣的Node模塊時會出錯。我怎樣才能做到這一點?Node.JS使用Require()添加訪問節點模塊CreateContext()

我使用沙盒模塊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

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