12

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?

1

1 Answer 1

26

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'));
Sign up to request clarification or add additional context in comments.

2 Comments

Is it possible to do in single line? something like const advertHandler = new require('./advertHandler')({test: "one"});
@A-letubby: Yes, but it's less readable: const handler = new (require('./advertHandler'))({test: "one"}); (note the () around the require call).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.