Module.prototype.module在`node_modules`中找不到模块

时间:2015-11-08 19:21:49

标签: javascript node.js node-modules

我正在尝试将全局require函数注入基于Module.prototype.require的vm全局上下文:

function createContext(filename, ctxt) {
// filename is an absolute path to file in same or subdirectory
// to dir with node_module directory
    let ctx = ctxt || {};
    let module = new Module(filename);

    for (let key in global) {
        if (global[key] === global) {
            ctx[key] = ctx;
        } else ctx[key] = global[key];
    }

    ctx.module = module;
    ctx.main = function() {
        return 1;
    };

    if (filename !== null) {
        filename = path.resolve(filename);

        ctx.__dirname = path.dirname(filename);
        ctx.__filename = path.basename(filename);
        console.log(filename);
        ctx.require = function(mod) {
            if (mod === 'bizubee lib') {

                return exports;
            }

            return module.require(mod);
        };
    }

    return ctx;
}

require然后适用于本地文件(require('./file'))和内置模块(例如' http',' fs')。但是我无法从最近的“node_modules”中加载已安装的模块。目录。这是我得到的错误:

module.js:338
    throw err;
    ^
Error: Cannot find module 'lazy-iterator'
    at Function.Module._resolveFilename (module.js:336:15)
    at Function.Module._load (module.js:286:25)
    at Module.require (module.js:365:17)
    at ctx.require (/home/ubuntu/workspace/bizubee/src/lib.js:171:21)
    at /home/ubuntu/workspace/bizubee/play/crap.jsl.js:5:12
    at ContextifyScript.Script.runInNewContext (vm.js:18:15)
    at Object.exports.runInNewContext (vm.js:49:17)
    at Object.runFileInNewContext (/home/ubuntu/workspace/bizubee/src/lib.js:217:8)
    at Object.<anonymous> (/home/ubuntu/workspace/bizubee/index.js:135:30)
    at Module._compile (module.js:430:26)

有什么想法吗?

提前谢谢!

0 个答案:

没有答案