C
C
ChernovGV2020-10-16 08:40:35
JavaScript
ChernovGV, 2020-10-16 08:40:35

What causes the "Xxxx is not a constructor" error when including a class via require in Node.js?

Hello!
I ran into a problem, for some reason the class connected via require is written to a constant as an object:

const LietnerBox = require('../entities/LietnerBox');

5f8931a725e13565562250.png
As a result, I get the error "LietnerBox is not a constructor" when I try to instantiate an object of this class.
Note that the RepeatResult class is also included, but it is defined as a class and does not cause problems.

If you connect the class inside the method, then the problem disappears.
const RepeatResult = require("../dto/RepeatResult");
// const LietnerBox = require('../entities/LietnerBox'); //получаю ошибку "LietnerBox is not a constructor"

class CardMover {
...
    /**
     * @param repeatResult {RepeatResult}
     * @return {LietnerBox}
     */
    _getNextBox(repeatResult) {
        const LietnerBox = require('../entities/LietnerBox'); //код выполняется корректно
        return new LietnerBox(1);
    }
...
}

module.exports = CardMover;


5f892cb703363214178260.png

Tell me why and what are the nuances of using require in Node.js?

LietnerBox class file

class LietnerBox {

    /**
     * @param num {Number}
     */
    constructor(num) {
        this._num = num;
        ...
    }
    ...
}

module.exports = LietnerBox;

Answer the question

In order to leave comments, you need to log in

2 answer(s)
C
ChernovGV, 2020-10-16
@ChernovGV

Dear Lynn "Coffeeman" , turned out to be right!


Lynn "Coffee Man" :
Wangyu cyclical addiction

The fact is that require in JS is not the same as import in java, or use in php.
It turns out that classes in JS cannot be imported for each other.

V
Vitaly, 2020-10-16
@vshvydky

for me, all connections should be at the beginning of the file, using the requester in the method is bad code.
I want to beautifully decompose into patterns, look in the direction of the composition.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question