如何在javascript中动态使用“require”?

问题描述 投票:0回答:1

我在“sample.js”文件中有一个javascript函数。是这样的:

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;

在另一个名为“institute.js”的文件中,我想动态地需要上述“test_xxx_API”文件。我有以下代码:

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

当我通过“node Institute.js”命令运行此代码时,出现以下错误:

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

但是“test_100_API.js”文件存在,并且位于当前文件夹中“institute.js”旁边。当我将

var insAPI = require(mapFile);
更改为
var insAPI = require("./test_100_API.js");
并为其指定确切路径而不是动态路径时,它工作正常。有人可以帮助我吗?

提前致谢

javascript node.js require
1个回答
0
投票

出现您遇到的问题是因为 Node.js 中的 require 期望模块的相对路径基于当前工作目录(运行 Node Institute.js 的位置),而不是相对于包含 require 语句的文件。

在您的情况下,mapFile 仅包含文件名('test_100_API.js'),但 Node.js 试图在运行 Node Institute.js 的当前目录中找到它。要解决此问题并允许基于存储在 mapDict 中的文件名的动态需求,您可以修改您的 Institute.js 代码,如下所示:

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
© www.soinside.com 2019 - 2024. All rights reserved.