如何在node.js javascript中限制对apis的访问?

我做了一些研究,找不到任何能让我成功的事情。

所以,我用require(..)从外部脚本加载.js ,每个脚本导出一个函数..

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 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'); 

(正如你所看到的,Node中的任何内置函数,比如console ,你想在safe_require模块中使用的函数都需要在sandbox对象中传递)