Search code examples
javascriptnode.jsmodule.exports

How to fix Error Cannot Find Module for nodejs


I have a function I've made in a .js file and I'm trying to import and use the function in a get route for an application build but i keep getting this error

internal/modules/cjs/loader.js:888
  throw err;
  ^

Error: Cannot find module './crawler/ocr-crawler.js'

this is how the function is set up:

async function OcrCrawlerTest(){

 // some code here
}

module.exports = {OcrCrawlerTest};

and this is how I am calling it:

const { OcrCrawlerTest } = require('./crawler/ocr-crawler.js');

im new to javascript so please give some detail in the solution

also if needed my path structure is set up as shown:

--- main directory 
    └── app.js
    └── crawler
         └── ocr-crawler.js
    └── routes
         └── crawler.js

Solution

  • In your "app.js" file, you can use the code below. NodeJS will walk through your directory to find the appropriate module.

    const { OcrCrawlerTest } = require('./crawler/ocr-crawler'); // remove ".js" at the end
    

    You can find more information in this document


    EDIT In case you're requiring OcrCrawlerTest from routes/crawler.js file, you need to provide the relative path from routes/crawler.js file to crawler/ocr-crawler.js file:

    const { OcrCrawlerTest } = require('../crawler/ocr-crawler');