Gnt*_*tem 5 javascript node.js
我做了一些研究,找不到任何让我的案子成功的东西.
所以,我.js从外部脚本加载require(..),每个脚本导出一个函数..
main.js
var main=10;
var mod1 = require("./mod1.js");
Run Code Online (Sandbox Code Playgroud)
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...;
}
Run Code Online (Sandbox Code Playgroud)
我看到了.json文件声明的一些方法,permissions如果是这样,它会授予对脚本的访问权限.如何在核心node.js apis中实现类似的功能?
根据您的具体需求,您可以使用该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');
Run Code Online (Sandbox Code Playgroud)
(正如您所看到的,Node的任何内置函数,例如console,您希望在safe_require需要在沙箱对象中传递的模块中使用)
| 归档时间: |
|
| 查看次数: |
1560 次 |
| 最近记录: |