Reputation: 592
I want to have a folder with javascript files and be able to programmatically run whatever is on them asynchronously. For example:
async.each(folder_files, function(content, cb){
run_script(content);
cb();
},function(err){
if(err){
console.log(err);
}else{
console.log("All scripts ran succesfully :D");
}
});
Is this even possible?
EDIT: Just to clarify, I want to be able to change the folder contents with any number of scripts and run them through the main JS file.
Upvotes: 1
Views: 8886
Reputation: 911
Here is a simple solution using async
, but you need to put all your scripts inside scripts
folder beside the main file
const fs = require('fs')
const exec = require('child_process').exec
const async = require('async') // npm install async
const scriptsFolder = './scripts/' // add your scripts to folder named scripts
const files = fs.readdirSync(scriptsFolder) // reading files from folders
const funcs = files.map(function(file) {
return exec.bind(null, `node ${scriptsFolder}${file}`) // execute node command
})
function getResults(err, data) {
if (err) {
return console.log(err)
}
const results = data.map(function(lines){
return lines.join('') // joining each script lines
})
console.log(results)
}
// to run your scipts in parallel use
async.parallel(funcs, getResults)
// to run your scipts in series use
async.series(funcs, getResults)
Upvotes: 6