5

我做了一些研究,找不到任何使我的案例成功的东西。

所以,我.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如何实现这样的目标?

4

1 回答 1

9

根据您的确切需求,您可能可以将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需要在沙盒对象中传递的模块)

于 2013-10-18T07:36:52.570 回答