0

I have an express.js block I want to refactor to be used in other parts of my webapp for example, I have function isPrime on my router file. I extract this block of code and put it in

./helpers/isPrime
    module.exports = function isPrime(num) {
        for(let i = 2 ; i < num ;i++){
            if(num % i == 0){
                return false;
            }
        }
        return true;
     }

when I added in route file I have this error Error: Cannot find module './helpers/isPrime' Require stack:

  • /Users/auser/Documents/SandBox/AE_Technical_Challenge/routes/challengeRouter.js
  • /Users/auser/Documents/SandBox/AE_Technical_Challenge/app.js
NinjaDeveloper
  • 1,620
  • 3
  • 19
  • 51
  • `when I added in route file`, please show how you're importing it. Be sure that wherever you're importing the file is relative to where the file exists. – Phix Mar 02 '21 at 04:36
  • plz: [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) your question has nothing in it that can lead to the root of your issue – x00 Mar 02 '21 at 07:21

1 Answers1

2

Here's how to debug this.

First, we know that the error is MODULE_NOT_FOUND, which means that you have a require statement that node failed to resolve.

Second, we know that it fails on a relative import, because of the dot in Cannot find module './helpers/isPrime'.

Third, we take a look at the require stack. The top line of that is AE_Technical_Challenge/routes/challengeRouter.js. This means that you have a require('./helpers/isPrime') statement in that file, and the resolution for this statement fails.

Relative imports expect the path to be relative to the current file, not entry-point. In other words, Node joins the directory the current file is in (AE_Technical_Challenge/routes) together with the relative require path (./helpers/isPrime). The result is AE_Technical_Challenge/routes/helpers/isPrime. The file is not there, so it fails.

If the structure of your project is like this:

.
├── routes/
│   └── challengeRouter.js
├── helpers/
│   └── isPrime.js
└── app.js

then inside the router file you want to do require('../helpers/isPrime'). The .. takes you from routes to project root, and then you navigate to the helper file.

Thus, the simplest solution is to just fix your import to correctly reference the isPrime file. Moreover, if you are using a modern editor like one of JetBrains IDEs or VSCode, they will auto-import everything for you so you don't have to manually type the require path.

If you are really set on requiring other modules as if you were in your project root, you can check the answers to this question for a multitude of options.

Marian
  • 3,789
  • 2
  • 26
  • 36