9

I have a javascript function in "sample.js" file. It is like this:

var mapDict = { '100': 'test_100.js', '200': 'test_200_API.js', '300': 'test_300_API.js' }

function mapAPI()
{
    this.version = 0.1;
}

mapAPI.prototype.getFileName = function( id ) {
   return mapDict[id]
}

module.exports = mapAPI;

in another file named "institute.js" I want to require the above "test_xxx_API" files dynamically. I have the following code:

const mapAPI  = require('../../sample.js');
const map     = new mapAPI();
const mapFile = map.getFileName("100");
var insAPI    = require(mapFile);

When I run this code by "node institute.js" command, I get the following error:

Error: Cannot find module './test_100_API.js'.

But the "test_100_API.js" file exists and is located in the current folder besides "institute.js". When I changed var insAPI = require(mapFile); to var insAPI = require("./test_100_API.js"); and give it the exact path instead of dynamic path, it works fine. Can anyone help me?

Thanks in advance

extempl
  • 2,987
  • 1
  • 26
  • 38
we.are
  • 409
  • 2
  • 6
  • 15
  • where in the disk are these dynamic files found, you nee dto include the full path, for example `require(__dirname+mapFile);` if on same folder else find the path they are under NOT just the filename the WHOLE path. – Nikos M. Nov 14 '18 at 18:05
  • 4
    then use this `require('./'+mapFile);` – Nikos M. Nov 14 '18 at 18:17
  • 1
    They are on the same folder. My problem is that when I use `var insAPI = require(mapFile)` and prints `mapFile` value it is exactly prints `./test_100_API.js' in the console. My code works correctly with `var insAPI = require("./test_100_API.js")` but gives me error with `var insAPI = require(mapFile);`. This is the strange part. – we.are Nov 15 '18 at 13:15
  • Take a look at this thread [link](https://stackoverflow.com/questions/42797313/webpack-dynamic-module-loader-by-require) But in resume what you have to do is **require(\`./${path}/file.js\`);** – Victor Oliveira Jul 04 '19 at 11:11
  • 3
    @NikosM., this approach is not working in react native. – Tushar Pandey Apr 13 '21 at 04:23

0 Answers0