0

I'm trying to make some discord bots, and I'm getting frustrated trying to use a class I created in another script. The script in question looks like this:

// utils.js

class BotUtils {
   constructor(param1, param2, ...) {
      this.param1 = param1;
      this.param2 = param2;
      ...
      }

    someMethod() {
    doSomething;
    }
}

module.exports = {BotUtils};

In my bot script, I have:

// bot.js
const botUtils = require('./BotUtils');

let utils = new BotUtils(param1, param2, ...);

And I get TypeError: BotUtils is not a constructor

I've also tried using new but it doesn't work. I need to construct the class with the specific parameters. What's the correct way to do this?

dbm
  • 35
  • 1
  • 6

1 Answers1

2

You are exporting an object with the class BotUtils as a property from your module. To create an instance of the class, you need to reference the property i.e.

let utils = new botUtils.BotUtils(param1, param2, ...);

If you want to export only the BotUtils class then you can do so by removing the brackets

module.exports = BotUtils;

Then when you require the module the class is what is returned, this is closer to your original code but with a small tweak

const BotUtils = require('./utils');

Additionally, if you are using ES modules, this gets a lot easier with named exports

import { BotUtils } from './utils'
James
  • 80,725
  • 18
  • 167
  • 237
  • Christ, I've been bashing my head against the desk for hours trying to fix this and it's that simple. Thanks! – dbm Dec 08 '19 at 00:04
  • Also I tried using ES modules but that was a whole other headache so I went back to the normal exports. Works now though. – dbm Dec 08 '19 at 00:14
  • @dbm that's a whole other [can of worms](https://stackoverflow.com/questions/39436322/node-js-syntaxerror-unexpected-token-import). It was on the off chance you were using ES6 already. – James Dec 08 '19 at 00:19