NodeJS & Electron: Async Multiple Required Files

2019-08-20 08:45发布

问题:

I wish to create an array of modules to require, to loop through the modules to require, require them asynchronously, and then callback. I have tried the below:

// async require module for other required modules
function asyncRequire (requireList, callback) {
    if (!Array.isArray(requireList)) {return};

    var index = -1;
    var loop = {}
    loop.next = function () {
        if (index < requireList.length) {
            var asyncOperation = function (j) {
                setTimeout(function() {
                    index++;
                    var item = requireList[index];
                    console.log(item);
                    window[item] = require(item);
                    loop.next();
                }, 10);
            }
            asyncOperation(requireList);
        } else {
            if (typeof callback === "function") {
                setTimeout(function() {
                    callback();
                }, 1000);
            }
        }
    }
    loop.next();
}

// usage example
var requireList = ['moduleName', 'moduleName2']

asyncRequire(requireList, callback)

function callback() {
    console.log("success");
}

However, although the path for require is correct, I get the error:

AssertionError
actual: undefined
expected: true
generatedMessage: false
message: "missing path"
name: "AssertionError"
operator:"=="
stack:"AssertionError: missing path↵    at Module.require (module.js:496:3)↵    at require (internal/module.js:20:19)↵    at asyncRequire.js:18:21"
__proto__: Error

I also feel that there may be a delay between the completion of the require, and the callback. Therefore, the callback could fail. Is this correct?

Please note this is a continuation of my question: Where/How Should I require multiple modules for performance?

回答1:

As far as i can remember you cannot require modules like this (dynamically/runtime) , only way i think you can do this is by manually reading the files via fs module during runtime. More details on how to do this is here : Loading Node.js modules dynamically based on route