我如何在JS中动态地要求模块、实例化对象和调用函数

How do i dynamically require module, instantiate object and call function in JS

本文关键字:实例化 模块 对象 函数 调用 JS 动态      更新时间:2023-09-26

构建一个节点应用程序,我一直在使用我构建的几个不同的比特币交换模块进行需求和操作。有时我想添加或删除一个交换,通过代码添加和删除对交换的所有硬编码引用是很痛苦的。

有办法做这样的事情吗?很抱歉,如果这是一个明显的问题——我对node和(编程)周末战士来说相对陌生。提前感谢您的意见。

//config.js    
var config = {}
config.exchanges = ['bitfinex', 'bitstamp', 'btce'];
module.exports = config;
//app.js
var config = require('./config');
var _= require('underscore');
_.each(config.exchanges, function(exchange){
    //obviously not correct, but how would I accomplish something like this?
    var Exchange = require('./api/exchange');
    var exchange = new Exchange();
    exchange.do_stuff();
});

这是一段在没有引用的情况下加载模型、控制器和api文件的代码:

  # Bootstrap models
  models_path = __dirname + "/models"
  fs.readdirSync(models_path).forEach (file) ->
    require models_path + "/" + file  if ~file.indexOf(".js")
  # Bootstrap controllers
  controllers_path = __dirname + "/controllers"
  fs.readdirSync(controllers_path).forEach (file) ->
    app.controllers[file.slice(0, -3)] = require(controllers_path + "/" + file)  if ~file.indexOf(".js")
    return
  # Bootstrap api
  api_path = __dirname + "/api"
  fs.readdirSync(api_path).forEach (file) ->
    app.api[file.slice(0, -3)] = require(api_path + "/" + file)  if ~file.indexOf(".js")
    return

希望它能帮助