HLW
HLW

Reputation: 47

How to export functions in modules?

Dear all I just started learning modules in javascript. This is my implementation of a module:

module.exports = function(logger_level) {
    this.info = function(message) {
        stdout(message);
    };
};

function stdout(message)
{
    process.stdout.write(message+'\n');
}

and I have to invoke it like this:

var logger = require('./js/logger.js');
var logger1 = new logger("info1");

logger1.info("info");

My question is how to change my implementation of the module so that I could invoke it like this:

var logger = require('./js/logger.js')("info");
logger.info("info");

Upvotes: 3

Views: 77

Answers (3)

Bartosz Gościński
Bartosz Gościński

Reputation: 1580

You're looking for a factory function. Applying it to your use case it would look like:

module.exports = function(logger_level) {
    return {
        info: function(message) {
            stdout(message);
        }
    };
};

function stdout(message)
{
    process.stdout.write(message+'\n');
}

Upvotes: 1

You can wrap your constructor function with an object and return an instance of your constructor function

module.exports = {

    return new function(logger_level) {
        this.info = function(message) {
            stdout(message);
        };
    };

}

And call it

var logger = require('./js/logger.js');
logger.info("info");

You can also make a singleton pattern to work with a single instance of your constructor function

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1074276

If you want to use it like that, there's no need for a constructor function at all:

module.exports = {
    info: function(message) {
        stdout(message);
    }
};

function stdout(message)
{
    process.stdout.write(message+'\n');
}

I just started learning modules in javascript.

Note that this isn't "modules in JavaScript" so much as it is "modules in NodeJS". JavaScript's modules, which weren't introduced until ES2015 ("ES6"), look and act quite different, but they aren't broadly-supported yet. When they are, your module might look like this:

// ES2015+ syntax
export default {
    info: function(message) {
        stdout(message);
    }
};

function stdout(message)
{
    process.stdout.write(message+'\n');
}

...and used like this:

import logger from './logger.js';
logger.info("info");

Upvotes: 2

Related Questions