Perfect way for requiring NodeBB modules?


  • Plugin & Theme Dev

    So what is the absolute best way to go around doing this?

    Doing something like module.require('../../etc') will break npm link. This lead to the use of module.parent.require('stuff'), which seems to work fine.

    However, pretend I have the following situation:

    • Plugin root
    • library.js - module.parent works fine here
    • lib
      • submoduleA.js - this is require'd from library.js. module.parent refers to library.js, module.parent.parent is necessary.
      • submoduleB.js - this is require'd from submoduleA.js, module.parent.parent.parent is necessary to access NodeBB modules.

    So what would be the best way to go from here to keep things sane and clean?


  • GNU/Linux Admin

    Can't say I ever encountered that specific use case, @mr_waffle 😄

    module.parent.require works great for the case you described above, as outlined in my blog post. In your case, you might want to pass in the library instead, if that helps keep things tidy for you:

    library.js

    var Posts = module.parent.require('./posts')
      , submoduleA = require('./submoduleA')(Posts);
    

    submoduleA.js

    module.exports = function(Posts) {
        var submoduleB = require('./submoduleB')(Posts);
    };
    

    submoduleB.js

    module.exports = function(Posts) {
        // Do stuff with Posts here
    };
    

  • Plugin & Theme Dev

    @julian Thanks, didn't think of that method! I'll give it a try!

    Edit: Hm actually don't think this will work in my case.


  • Plugin & Theme Dev

    To get back on this, I have currently solved it in the following way:
    ###/lib/nodebb.js:

    module.exports = {
    	"Meta": module.parent.parent.require('./meta'),
    	"User": module.parent.parent.require('./user'),
    	"Plugins": module.parent.parent.require('./plugins'),
    	"SocketIndex": module.parent.parent.require('./socket.io/index'),
    	"ModulesSockets": module.parent.parent.require('./socket.io/modules'),
    	"db": module.parent.parent.require('./database')
    }
    

    ###library.js:

    var NodeBB = require('./lib/nodebb');
    

    ###/lib/submoduleX.js:

    var NodeBB = module.require('./nodebb'),
    	db = NodeBB.db,
    	User = NodeBB.User,
    	Plugins = NodeBB.Plugins;
    

    ##Why this works
    I read somewhere that require caches the files you load. That means that if require my nodebb.js from library.js, I can later load nodebb.js from any submodule I want and it will work.


Log in to reply
 

Suggested Topics

  • 3
  • 1
  • 1
  • 4
  • 1
| |