简体   繁体   中英

How to run all javascript files in a folder with NodeJS?

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM