根据您的确切需求,您可能可以将vm
模块(内置于 Node)用作一种沙盒:
var vm = require('vm');
var fs = require('fs');
var safe_require = function(mod) {
var code = fs.readFileSync(require.resolve(mod));
var sandbox = {
console : console,
module : {},
require : function(mod) {
// as a simple example, we'll block any requiring of the 'net' module, but
// you could implement some sort of whitelisting/blacklisting for modules
// that are/aren't allowed to be loaded from your module:
if (mod === 'net') {
throw Error('not allowed');
}
// if the module is okay to load, load it:
return require.apply(this, arguments);
}
};
vm.runInNewContext(code, sandbox, __filename);
return sandbox.module.exports;
};
var mod = safe_require('./mod1');
console
(如您所见,您想要在模块中使用的任何 Node 内置函数,例如,safe_require
需要在沙盒对象中传递的模块)