How to require a file in node.js and pass an argument in the request method, but not to the module?

前端 未结 3 1440
梦谈多话
梦谈多话 2021-02-03 23:47

I have a module.js that must be loaded; In order to work needs objectX;

How do I pass the objectX to the module.js in the require method provided by node.js?

tha

3条回答
  •  死守一世寂寞
    2021-02-04 00:16

    The module that you write can export a single function. When you require the module, call the function with your initialization argument. That function can return an Object (hash) which you place into your variable in the require-ing module. In other words:

    main.js

    var initValue = 0;
    var a = require('./arithmetic')(initValue);
    // It has functions
    console.log(a);
    // Call them
    console.log(a.addOne());
    console.log(a.subtractOne());
    

    arithmetic.js:

    module.exports = function(initValue) {
      return {
        addOne: function() {
          return initValue + 1;
        },
        subtractOne: function() {
          return initValue - 1;
        },
      }
    }
    

提交回复
热议问题