简体   繁体   中英

Access another module.exports function from the same file node.js

To make it a bit more clear to what I'm trying to achieve.

I have a server running which includes many module, and one of the module use to check if the user role is an admin or not.

in Server.js

   var loginAPI = require('myModule')(argStringType),
       express = require('express');

   var app = express();

Now that in the myModule.js I have few functions that already been implemented and just wanted to add one more, but this function really doesn't need to be call from the server.js instead it will be call once the person visit the URL , so I want to add something like this to the myModule.js

in myModule.js

app.get( "/post/:postid", function( req, res ) {
  var id = req.param('postid');
  return getContent( postid );
});



// Module.exports
module.exports = function ( arg ) {

  return {

    getContent: function ( id ) { },

    getHeader: function ( id ) { };
};

So as you can see from the above, I have two function which is in the module.exports and they worked fine no problem except the one which is outside the module.exports that one work if I don't try to call the getContent , but that is what I'm trying to achieve. When someone visit the site by entering the URL in that format the app.get should be fire and do whatever is implemented to do.

Make sure you realize each module in Node.js has its own scope. So

ModuleA:

var test = "Test output string";
require('ModuleB');

ModuleB:

console.log(test);

Will simply output undefined .

With that said, I think this is the style of module you're looking for:

server.js:

var app = //instantiate express in whatever way you'd like
var loginApi = require('loginModule.js')(app);

loginModule.js:

module.exports = function (app) {

  //setup get handler
  app.get( "/post/:postid", function( req, res ) {
    var id = req.param('postid');
    return getContent( postid );
  });

  //other methods which are indended to be called more than once
  //any of these functions can be called from the get handler
  function getContent ( id ) { ... }

  function getHeader ( id ) { ... }

  //return a closure which exposes certain methods publicly
  //to allow them to be called from the loginApi variable
  return { getContent: getContent, getHeader: getHeader };
};

Obviously, adjust to fit your actual needs. There are lots of ways to do the same type of thing, but this fits closest with your original example. Hopefully that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM