Node.js - asynchronous module loading

后端 未结 4 1576
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-04 07:35

Is it possible to load a Node.js module asynchronously?

This is the standard code:

var foo = require(\"./foo.js\"); // waiting for I/O
foo.bar();
         


        
4条回答
  •  时光说笑
    2020-12-04 08:35

    The npm module async-require can help you to do this.

    Install

    npm install --save async-require
    

    Usage

    var asyncRequire = require('async-require');
    
    // Load script myModule.js 
    asyncRequire('myModule').then(function (module) {
        // module has been exported and can be used here
        // ...
    });
    

    The module uses vm.runInNewContext(), a technique discussed in the accepted answer. It has bluebird as a dependency.

    (This solution appeared in an earlier answer but that was deleted by review.)

提交回复
热议问题