1

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.

3
  • What do you mean when you say "run them asynchronously"? Do you mean "sequentially" one after the other or do you want them to run in parallel without affecting the running of your main program. Two very different problems. Commented May 28, 2018 at 3:44
  • Also, are they expecting to be run as node.js modules? Do you want them to share access to the global space in your main JS file? Or be isolated from your main JS file? Are you trying to get any results back from any of them? Do you care about the order they are run? Commented May 28, 2018 at 3:46
  • No, don't care about order, async or sync isn't as important for now, no need to get results back, no need for callbacks, I just want it to look for files at a folder at root with a generic name Commented May 28, 2018 at 5:34

1 Answer 1

6

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.