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?

Prakash Pazhanisamy
  • 997
  • 1
  • 15
  • 25
Itsmeromka
  • 3,621
  • 9
  • 46
  • 79

1 Answers1

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'));
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Is it possible to do in single line? something like `const advertHandler = new require('./advertHandler')({test: "one"});` – A-letubby Aug 31 '17 at 13:13
  • 3
    @A-letubby: Yes, but it's less readable: `const handler = new (require('./advertHandler'))({test: "one"});` (note the `()` around the `require` call). – T.J. Crowder Aug 31 '17 at 14:46