Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Namespaces in node.js with require

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.

like image 861
Miles McCrocklin Avatar asked Jul 22 '12 16:07

Miles McCrocklin


People also ask

Why is require () used in Node JS?

In NodeJS, require() is a built-in function to include external modules that exist in separate files. require() statement basically reads a JavaScript file, executes it, and then proceeds to return the export object.

How do you define require in node JS?

You can think of the require module as the command and the module module as the organizer of all required modules. Requiring a module in Node isn't that complicated of a concept. const config = require('/path/to/file'); The main object exported by the require module is a function (as used in the above example).

What is namespace in node JS?

Namespaces are a TypeScript-specific way to organize code. Namespaces are simply named JavaScript objects in the global namespace. This makes namespaces a very simple construct to use. Unlike modules, they can span multiple files, and can be concatenated using outFile .

Can we use import instead of require in node JS?

You can now start using modern ES Import/Export statements in your Node apps without the need for a tool such as Babel.


1 Answers

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 ..

like image 174
Florian Margaine Avatar answered Sep 24 '22 18:09

Florian Margaine