Littlebobbydroptables
Littlebobbydroptables

Reputation: 3731

Node.js require class with constructor parameter

I have a class

class advertHandler {
    constructor(projects) {
        this.projects = projects;
    }

    getProject(name) {
        return this.projects[name];
    }
}


module.exports = new advertHandler(projects);

When I try to use it like this

const advertHandler = require('./advertHandler')(projectsArray);
advertHandler.getProject('test');

And it throws an exception, require is not a function, but without a constructor, everything is fine, so the question is how to use the class constructor with require?

Upvotes: 12

Views: 41020

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074395

It's not saying require is not a function, it's saying require(...) is not a function. :-) You're trying to call the result of require(...), but what you're exporting (an instance of advertHandler) isn't a function. Also note that in advertHandler.js, you're trying to use a global called projects (on the last line); ideally, best not to have globals in NodeJS apps when you can avoid it.

You just want to export the class:

module.exports = advertHandler;

...and then probably require it before calling it:

const advertHandler = require('./advertHandler');
const handler = new advertHandler({test: "one"});
console.log(handler.getProject('test'));

E.g.:

advertHandler.js:

class advertHandler {
    constructor(projects) {
        this.projects = projects;
    }

    getProject(name) {
        return this.projects[name];
    }
}

module.exports = advertHandler;

app.js:

const advertHandler = require('./advertHandler');
const handler = new advertHandler({test: "one"});
console.log(handler.getProject('test'));

Upvotes: 26

Related Questions