How can I share module-private data between 2 files in Node?

后端 未结 3 1936
深忆病人
深忆病人 2021-01-28 01:21

I would like to have a module for Node.js that is a directory with several files. I\'d like some vars from one file to be accessible from other file, but not from the files exte

3条回答
  •  渐次进展
    2021-01-28 01:34

    I'd like some vars from one file to be accessible from other file, but not from the files external to the module

    Yes, it is possible. You can load that other file into your module and hand it over a privileged function that offers access to specific variables from your module scope, or just hand it over the values themselves:

    index.js:

    var foo = 'some value';
    module.exports.additional = require('./additional.js')(foo);
    module.exports.extra = require('./extra.js')(foo);
    

    extra.js:

    module.exports = function(foo){
      // some magic here
      var bar = foo; // foo is the foo from index.js
      // instead of assigning the magic to exports, return it
    };
    

    additional.js:

    module.exports = function(foo){
      // some magic here
      var qux = foo; // foo is the foo from index.js again
      // instead of assigning the magic to exports, return it
    };
    

提交回复
热议问题