Exporting a module Node.js

This question already has an answer here:

  • In Node.js, how do I “include” functions from my other files? 20 answers

  • Only requiring a module A somewhere (in module B, for example) doesn't make the functions of A accessible in other modules. Normally, they're not even accessible in module B.

    To access functions (or any values) from another module, that other module has to export them. The following scenario will not work:

    // module-a.js
    function firstFunction () {}
    function secondFunction () {}
    
    // module-b.js
    var helper_handleSentences = require('/handleSentences.js'); 
    // do something with 'helper_handleSentences'
    module.exports = function (a) {
      return helper_handleSentences(a);
    }
    

    As you can see, module-a.js doesn't export anything. Thus, the variable a holds the default export value, which is an empty object.

    In your situation, you can either

    1. require both modules in mainModule.js

    // handleSentences.js
    function doSomethingSecret () {
      // this function can only be accessed in 'handleSentences.js'
    }
    function handleSentences () {
      // this function can be accessed in any module that requires this module
      doSomethingSecret();
    }
    module.exports = handleSentences;
    
    // formatModule.js
    var helper_handleSentences = require('/handleSentences.js'); 
    // do something with 'helper_handleSentences'
    module.exports = function (a) {
      return helper_handleSentences(a);
    };
    
    // mainModule.js
    var helper_handleSentences = require('/handleSentences.js');
    var helper_formatModule = require('/formatModule.js'); 
    // do something with 'helper_handleSentences' and 'helper_formatModule'
    

    2. merge the exported values of both modules into one object

    // handleSentences.js
    function doSomethingSecret () {
      // this function can only be accessed in 'handleSentences.js'
    }
    function handleSentences () {
      // this function can be accessed in any module that requires this module
      doSomethingSecret();
    }
    module.exports = handleSentences;
    
    // formatModule.js
    var helper_handleSentences = require('/handleSentences.js'); 
    // do something with 'helper_handleSentences'
    function formatModule (a) {
      return helper_handleSentences(a);
    };
    module.exports = {
      handleSentences: helper_handleSentences,
      format: formatModule
    };
    
    // mainModule.js
    var helper_formatModule = require('/formatModule.js');
    // use both functions as methods
    helper_formatModule.handleSentences();
    helper_formatModule.format('...');
    
    链接地址: http://www.djcxy.com/p/97016.html

    上一篇: 如何在nodjs中收集用户自定义函数?

    下一篇: 导出模块Node.js