Warning: count(): Parameter must be an array or an object that implements Countable in /customers/d/f/8/sveitech.dk/httpd.www/wp-content/plugins/css-javascript-toolbox/framework/events/subjects/hook.subject.php on line 81 Warning: count(): Parameter must be an array or an object that implements Countable in /customers/d/f/8/sveitech.dk/httpd.www/wp-content/plugins/css-javascript-toolbox/framework/events/subjects/hook.subject.php on line 82 Warning: count(): Parameter must be an array or an object that implements Countable in /customers/d/f/8/sveitech.dk/httpd.www/wp-content/plugins/css-javascript-toolbox/framework/events/subjects/hook.subject.php on line 81 Warning: count(): Parameter must be an array or an object that implements Countable in /customers/d/f/8/sveitech.dk/httpd.www/wp-content/plugins/css-javascript-toolbox/framework/events/subjects/hook.subject.php on line 82 Nodejs Module Implementation | Sveitech

Nodejs Module Implementation

In nodejs, separate javascript code files can be imported via the require() function call. The following javascript illustrates how this is accomplished.

function require(filename) {
    // Do not load a file, if we already loaded it once.
    if(filename in require.cache) {
        return require.cache[filename];
    }

    // The Function object is part of base javascript and is available in browsers,
    // and in nodejs. The readFile functions is assumed to be available. Use an ajax
    // call to get a file, or the 'fs' module in nodejs to read a file.
    //
    // The Function() function creates a new js function, with a body from a string.
    // Basically, we are creating a new function with the body loaded from a file.
    var code = new Function('exports, module', readFile(filename));

    var exports = {};
    var module = {
        exports: exports
    };

    // Call our file-loaded function. Inside the file, a user can assign objects
    // directly to the exports object, or override the module.exports object,
    // to return functions or lists for example.
    code(exports, module);

    // Cache loaded file, to avoid loading it more than once if multiple
    // require() calls are made to the same file.
    require.cache[filename] = module.exports;

    return module.exports;
}

With the custom require function we can now create modules in separate files like this:

//module.js
exports.myFunction = function() {
    return 20;

// Alternatively, the module.exports can be used to return custom objects,
// instead of attaching to the exports object. Note that if you assign anything to this,
// you cannot use any assignments to the exports object anymore.
module.exports = function() {
    return 100;
}
};
var mod = require('module.js');

mod.myFunction();

// Or if the module used module.exports
mod();

Sveistrup Technologies