有比使用
eval:
vm模块更好的方法。
例如,这是我的
execfile模块,该模块
path在
context或全局上下文中评估脚本:
var vm = require("vm");var fs = require("fs");module.exports = function(path, context) { context = context || {}; var data = fs.readFileSync(path); vm.runInNewContext(data, context, path); return context;}可以这样使用:
> var execfile = require("execfile");> // `someGlobal` will be a global variable while the script runs> var context = execfile("example.js", { someGlobal: 42 });> // And `getSomeGlobal` defined in the script is available on `context`:> context.getSomeGlobal()42> context.someGlobal = 16> context.getSomeGlobal()16其中
example.js包含:
function getSomeGlobal() { return someGlobal;}此方法的最大优点是,您可以完全控制已执行脚本中的全局变量:您可以传入自定义全局变量(通过
context),并且脚本创建的所有全局变量都将添加到中
context。调试也更容易,因为将使用正确的文件名报告语法错误等。



