Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Function in module.exports "is not a function"? – nodejs

I’m trying to use badPort function inside another function (getPort) in module.exports like so:

DEFAULT_PORT = 80;

module.exports = {
        badPort:
                (c_port, min=80, max=90) => {
                        return isNaN(c_port) || !between(c_port, min, max);
                },
        getPort:
                (c_port, min=80, max=90) => {
                        console.log(this.badPort(c_port));
                        return this.badPort(c_port) ? 80 : c_port;
                },
};     

However, when I use this.badPort(c_port) it throws an exception:

TypeError: this.badPort is not a function

But it’s clearly a function as initialised right above it.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

If however I take out the (), this.badPort always returns undefined.

Why is this happening and how would I be able to correctly use the function inside module.exports? Is it possible to also declare the "Global variable" DEFAULT_PORT in module.exports this way?

>Solution :

You can do it, by changing this to module.exports:

DEFAULT_PORT = 80;

module.exports = {
        badPort:
                (c_port, min=80, max=90) => {
                        return isNaN(c_port) || !between(c_port, min, max);
                },
        getPort:
                (c_port, min=80, max=90) => {
                        console.log(module.exports.badPort(c_port));
                        return module.exports.badPort(c_port) ? 80 : c_port;
                },
};

And about second question… you would have to redefine your module, to use that variable externally, like this:

module.exports.DEFAULT_PORT = 80;

Then you will have access to it:

var mod = require('mymodule');
console.log(mod.DEFAULT_PORT);

I am not aware of any other way.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading