简体   繁体   中英

Preventing relative require calls from modules in a specific folder

This will sound odd, but I'd like all modules in a specific directory to only be able to require resources out of node_modules and not from any other part of the application.

In a specific directory:

  • require('fs') -- should work
  • require('../../something') -- denied
  • require('./another') -- denied

Is anything like this remotely possible in Node?

You could make a module that'll act like a require-proxy:

module.exports.require2 = function() {
    if (arguments[0][0] !== '.') {
        return require.apply(this, arguments);
    } else {
        throw new Error('Can\'t require relative modules');
    }
}

Of course, this would be opt-in by the developers:

var require2 = require('require2');
var fs = require2('fs'); //everything's good
var fss = require2('./fss'); //throws an error

Kind of a similar idea to thlorenz's proxyquire .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM