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

Node.JS Adding access Node Modules using Require() to a CreateContext()

本文关键字:访问 节点 模块 添加 Require 使用 CreateContext      更新时间:2023-09-26

在我的应用程序我CreateContext,然后RunInContext。我需要在上下文中添加仅对某些节点模块的访问。我知道如何添加我自己的Javascript方法,但得到错误时,我添加节点模块,如async和http。我该怎么做呢?

我使用沙盒模块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);

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