Randomly run a node script file
Solution 1:
First things first, define "randomly". Do you mean every set amount of time a random file is run? Second, do you wish for the worker scripts' lives dependent on the master?
If i get what you mean, then this is simple enough
let {fork} = require("child_process")
setInterval(() => {
let scripts = ["script1.js", "script2.js", "script3.js"] //you can provide full path
let randomScript = scripts[Math.floor(Math.random() * Math.floor(scripts.length))]
fork(randomScript) //optionally, you can inherit stdio if you wish to see output
}, 20000) //time period in ms, in this case 20 seconds
I used fork here, which will only work with js scripts, but if you wish to execute a file or spawn another process I would suggest looking here
Solution 2:
Create a master.js with code
const {exec} = require('child_process');
function getRandomNumberBetween(min,max){
return Math.floor(Math.random()*(max-min+1)+min);
}
switch (getRandomNumberBetween(1,3)) {
case 1:
exec('forever start script1.js')
break;
case 2:
exec('forever start script2.js')
break;
case 3:
exec('forever start script3.js')
break;
default:
break;
}
run the file node master