Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use "require" dynamically in javascript?

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

like image 861
we.are Avatar asked May 03 '26 10:05

we.are


1 Answers

The issue you're encountering arises because require in Node.js expects relative paths to modules based on the current working directory (where you run node institute.js), not relative to the file that contains the require statement.

In your case, mapFile contains just the filename ('test_100_API.js'), but Node.js is trying to find it in the current directory where you are running node institute.js. To fix this and allow for dynamic requires based on filenames stored in mapDict, you can modify your institute.js code as follows:

const path = require('path');
const mapAPI = require('../../sample.js');

const map = new mapAPI();
const mapFile = map.getFileName("100");

// Construct the full path to the module using path.join
const modulePath = path.join(__dirname, mapFile);

// Now require the module using the constructed path
const insAPI = require(modulePath);

// Now you can use insAPI as needed
like image 58
Jhayvee Arai Avatar answered May 05 '26 22:05

Jhayvee Arai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!