Home > database >  import by module.exports from external file in NodeJS?
import by module.exports from external file in NodeJS?

Time:10-07

I am trying to import a function from another file. I tried by doing this:

main.js:

const oauth2 = require('./utils/oauth2');
function startOAuth() {
  var token = oauth2.OAuth2.getToken();
}

utils/oauth2.js:

module.exports =  (function() {

    window.OAuth2 = {
        
        /**
         * Initialize
         */
        init: function() {
            this._key = "token";
        },
        /**
         * Get Token
         * 
         * @return OAuth2 access token if it exists, null if not.
         */
         getToken: function() {
            try {
                return window['localStorage'][this._key];
            }
            catch(error) {
                return null;
            }
         }
       };
    
    OAuth2.init();
})();

I get the following error:

Uncaught TypeError: Cannot read properties of undefined (reading 'getToken')

What did I do wrong? Why does NodeJS not find the getToken() function? Thank you very much for your help!

PS: I know here is the wrong place to say I am a beginner but I am one ;)

CodePudding user response:

You're exporting a result of calling a function without a return. What you've assigned to the module.exports is a pattern called Immediately-invoked-function-expression.

The code should work if you instead assigned OAuth to a variable, called init() right after the declaration and then export it.

const OAuth2 = {
  /**
   * Initialize
   */
  init: function () {
    this._key = "";
  },
  /**
   * Get Token
   *
   * @return OAuth2 access token if it exists, null if not.
   */
  getToken: function () {
    try {
      return window["localStorage"][this._key];
    } catch (error) {
      return null;
    }
  },
};

OAuth2.init();

module.exports = OAuth2;
  • Related