我做了一些研究,但找不到任何能让我的案例成功的东西。
所以,我正在加载.js
从外部脚本require(..)
,每个脚本导出一个函数..
main.js
var main=10;
var mod1 = require("./mod1.js");
mod1.js
module.exports=function(){
console.log('loaded');
var net=require('net'); // i don't want it to be able to require certain node.js apis
net.create...;
}
我看到了一些方法.json
文件声明了permissions
如果是这样,它会授予对脚本的访问权限。对于核心 Node.js api 如何实现类似的功能?
根据您的具体需求,您可能可以使用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');
(如您所见,Node 的任何内置函数,例如console
,您想要在模块中使用safe_require
需要在沙箱对象中传递)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)