Namespaces in node.js with require
Asked Answered
C

1

8

I am playing around and learning about vows with a personal project. This is a small client side library, with testing done in vows. Therefore, I must build and test a file that is written like this:

(function(exports) { 
    var module = export.module = { "version":"0.0.1" }; 
    //more stuff
})(this);

In my testing (based off of science.js, d3, etc.) requires that module like so:

require("../module");

I continued to get a "module not defined error" when trying to run the tests, so I went to a repl and ran:

require("../module")

and it returned:

{ module: { version: "0.0.1" } }

I realize I could do something like:

var module = require("../module").module;

but feel like I am creating a problem by doing it that way, especially since the libraries that I based this project on are doing it in the format I described.

I would like for my project to behave similar to those which I based it off of, where:

require("../module");

creates a variable in this namespace:

module.version; //is valid.

I have seen this in a variety of libraries, and I am following the format and thought process to the T but believe I might be missing something about require behavior I don't know about.

Camden answered 22/7, 2012 at 16:40 Comment(1)
Related: Node.js namespacingEricaericaceous
G
18

There is no problem creating it this way. Modules define what they return in the module.exports object. By the way, you don't actually need self executing functions (SEF), there is no global leakage like in browsers :-)

Examples

module1.js:

module.exports = {
    module: { 'version': '0.1.1' }
};

main.js:

var module1 = require( './module1.js' );
// module1 has what is exported in module1.js

Once you've understood how this works, you can easily export the version number right away if you want to:

module1.js:

module.exports = '0.1.1';

main.js:

var module1 = require( './module1.js' );
console.log( module1 === '0.1.1' ); // true

Or if you want some logic, you can easily extend your module1.js file like this:

module.exports = ( function() {
    // some code
    return version;
} () ); // note the self executing part :-)
// since it's self executed, the exported part
// is what's returned in the SEF

Or, as many modules do, if you want to export some utility functions (and keep others "private"), you could do it like this:

module.exports = {
    func1: function() {
        return someFunc();
    },

    func2: function() {},

    prop: '1.0.0'
};

// This function is local to this file, it's not exported
function someFunc() {
}

So, in main.js:

var module1 = require( './module1.js' );
module1.func1(); // works
module1.func2(); // works
module1.prop; // "1.0.0"
module1.someFunc(); // Reference error, the function doesn't exist

Your special case

About your special case, I wouldn't recommend doing it like they're doing.

If you look here: https://github.com/jasondavies/science.js/blob/master/science.v1.js

You see that they're not using the var keyword. So, they're creating a global variable.

This is why they can access it once they require the module defining the global variable.

And by the way, the exports argument is useless in their case. It's even misleading, since it actually is the global object (equivalent of window in browsers), not the module.exports object (this in functions is the global object, it'd be undefined if strict mode were enabled).

Conclusion

Don't do it like they're doing, it's a bad idea. Global variables are a bad idea, it's better to use node's philosophy, and to store the required module in a variable that you reuse.

If you want to have an object that you can use in client side and test in node.js, here is a way:

yourModule.js:

// Use either node's export or the global object in browsers
var global = module ? module.exports : window.yourModule;

( function( exports ) {
    var yourModule = {};
    // do some stuff
    exports = yourModule;
} ( global ) );

Which you can shorten to this in order to avoid creating the global variable:

( function( exports ) {
    var yourModule = {};
    // do some stuff
    exports = yourModule;
} ( module ? module.exports : window.yourModule ) );

This way, you can use it like this on the client-side:

yourModule.someMethod(); // global object, "namespace"

And on the server side:

var yourModule = require( '../yourModule.js' );
yourModule.someMethod(); // local variable :-)

Just FYI, .. means "parent directory". This is the relative path of where to get the module. If the file were in the same directory, you'd use ..

Genocide answered 22/7, 2012 at 17:4 Comment(5)
Thanks Florian, this cleared a lot of issues up on how Node handles require and the module's namespace.Camden
Though, this is a client side library that I am creating, and have unit tests for it with vows via node. That being said, I think the SEF is a necessity, but, when I include the SEF it makes require("../module) return {module:{"stuff":"value" }} so, I'm wrapping a SEF with node's own manager that handles namespace issues, so my module seems to become relatively useless, I based this testing methodology off of: science.js, d3.js and dc.js. Rather than setting a variable to the exports: var d3 = require("d3"); in all the tests it does: require("d3"); and calls d3 directly.Camden
I don't know why this behavior occurs, though it seems to work really well for building, testing and maintaining client side libraries with node. I don't know what is going on, and if you could take a look at it I would be very appreciative. If not, thanks a lot you definitely cleared up some stuff I had with working and creating server side modules.Camden
If you like this answer, upvote it! :) I don't get what you mean in your comment though. If you feel that you need to expand on your problem, don't hesitate to edit your question.Genocide
@MilesMcCrocklin I edited my answer to add an explanation about your special case at the end :)Genocide

© 2022 - 2024 — McMap. All rights reserved.