I have some nodejs code that will act as an arbiter to a game played by bots.
Every bot will be it's own file, with a few predefined functions with fixed names (every bot will call its functions the same names and arguments, like PlayRound()).
Now I would like to, at runtime, add the bots in the game. Like I would tell the arbiter botName1, and it would look for a file called botName1.js inside the bots folder, then be able to call botName1.PlayRound() later on.
Since require only seems to work with literal static strings, and won't work with runtime values, is there even a way to do this?
sample code:
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();
}
}
});
require, does work with runtime values in nodejs.var m = "fs"; var fs = require(m);is perfectly valid in node.