代码之家  ›  专栏  ›  技术社区  ›  Kaito Kid

运行时从文件动态加载函数

  •  0
  • Kaito Kid  · 技术社区  · 7 年前

    我有一些nodejs代码可以作为机器人玩游戏的仲裁者。

    每个bot都是它自己的文件,其中有一些预定义的 functions 使用固定名称(每个bot都将使用相同的名称和参数调用其函数,例如 PlayRound() )

    现在我想,在 runtime ,在游戏中添加机器人程序。就像我告诉仲裁人 botName1 它会在bots文件夹中查找名为botname1.js的文件,然后能够调用 botName1.PlayRound() 后来。

    自从 require 似乎只使用文字静态字符串,而不使用运行时值,是否有一种方法可以做到这一点?

    样例代码:

    const readline = require('readline');
    const readLine = readline.createInterface({ input: process.stdin });
    
    var players = []
    var playerFiles = [];
    
    readLine.on('line', (ln) => {
    
        var ws = ln.split(' ');
    
        if (ws[0].toLowerCase() === 'add') {
            players[players.length] = ws[1];
            // I would like to add the file corresponding to the name here
        } else if (ws[0].toLowerCase() === 'list'){
            console.log('There are currently ' + players.length + ' players registered:');
            for (var p in players) {
                console.log(players[p]);
            }
        } else if (ws[0].toLowerCase() === 'start'){
            // I would like to do this here
            for (var playerFile in playerFiles) {
                playerFiles[playerFile].PlayRound();
            }
        }
    
    });
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   Himanshu Singh    7 年前

    1. botname botfilepath
    2. botfile botfunction

    bots

    const fs        = require( "fs" ),
          path      = require( "path" ),
          botsDir   = path.join( __dirname, "bots" );
    
    /** One time read to fetch all the bot files in bots dir */
    const files         = fs.readdirSync( botsDir ),
          /** Here we create the map of bot and bot file path */
          availableBots = files
                            .reduce( ( botMap, file ) => Object.assign( botMap, { 
                                [ file.replace(".js", "") ] : path.join( botsDir, file ) 
                            } ), {} );
    
    // Your code
    const botThatWillBeJoiningAtRuntime = "BotC"; // This would be some calculation to determine bot that joins at runtime.
    
    /** Here we safely require the bot file only if we have one corresponding to the bot that is joining */
    if ( availableBots[botThatWillBeJoiningAtRuntime] ) {
        const botFunc = require( availableBots[botThatWillBeJoiningAtRuntime] );
    }
    

    if

        2
  •  1
  •   Yash Thakor    7 年前

     fs.readdirSync(PATHOFDIRECTORYCONTAININGFILEs)
           .forEach((file) =>  {
            var name = file.replace('.js', '');
            if(name === botname) {
              require('./' + file).PlayRound();
            }
        });
    

     const readline = require('readline');
     const fs = require('fs);
     const readLine = readline.createInterface({ input: process.stdin });
    
     var players = []
     var playerFiles = [];
    
     readLine.on('line', (ln) => {
    
    var ws = ln.split(' ');
    
    if (ws[0].toLowerCase() === 'add') {
        players[players.length] = ws[1];
        //
    } else if (ws[0].toLowerCase() === 'list'){
        console.log('There are currently ' + players.length + ' players 
            registered:');
        for (var p in players) {
            console.log(players[p]);
        }
    } else if (ws[0].toLowerCase() === 'start'){
        // I would like to do this here
    
       fs.readdirSync(__diname)
       .forEach((file) =>  {
           for (var playerFile in playerFiles) {
             var name = file.replace('.js', '');
             if(name === playerFile) {
             require('./' + file).PlayRound();
            }
         }
      });
    });
    
    推荐文章