node.js需要虚拟机脚本中的模块

时间:2014-06-06 20:17:25

标签: javascript node.js

我正在使用运行外部脚本的node.js创建命令行界面

> myapp build "path/to/script.js"

myapp是一个node.js应用程序,它执行作为命令行参数传递的脚本 为了简单起见,它基本上是这样做的:

var vm = require("vm");
var fs = require("fs");

var code = fs.readFileSync(scriptPath, { encoding: "utf8" }); // read "path/to/script.js"
var script = vm.createScript(code, scriptPath);
var context = vm.createContext({ require: require });

script.runInNewContext(context);

" path / to / script.js"的内容看起来像这样:

var fs = require("fs"); // this works
var date = require("./date.js"); // supposed to load "path/to/date.js" but fails

我的问题是require()在外部脚本中无法正常工作。它适用于" native"模块如fs但在本地文件上失败,可能是因为它不知道在哪里查找模块。

我考虑过简单地使用以下代码:

require(scriptPath);

但是我无法注入自己的脚本上下文。

我可以编写自己的require函数来模拟内置需求,但是开始在scriptPath中查找模块,但这看起来有点单调乏味......

1 个答案:

答案 0 :(得分:2)

我已使用sandboxed-module来解决类似问题。

var Sandbox = require('./sandboxed-module')
Sandbox.require(scriptPath);

Sandbox.require从磁盘加载代码并在新的上下文中运行它。它提供了沙箱特定的require功能,可让您调整require的工作方式。