user12669401
user12669401

Reputation: 249

Execute Multiple .js Files From Terminal In Sequence

I have about 100 JS files with each having different script.

file1.js , file2.js , file3.js , ... , file100.js

Right now, to execute each file I have to go to my terminal and do this:

node file1
node file2
node file3
.
.
node file100

That means I have to do this 100 times in the terminal. Is there a script to write in a JS file so I can execute ONLY ONE JS file that would execute all the 100 JS files in sequence?

I also want to give 3 seconds waiting between each execution which I believe I can achieve with the following code:

var interval = 3000;
var promise = Promise.resolve();

promise = promise.then(function () {

return new Promise(function (resolve) {
setTimeout(resolve, interval);
});
});

Any suggestion how to execute all the 100 JS files without typing node file# 100 times in the terminal?

Upvotes: 0

Views: 386

Answers (1)

Ahmed Magdy
Ahmed Magdy

Reputation: 1226

here is a script that does that, you can also choose a different file format rather than

node file1 
..
node filex 

you can do this file1,file2,file3...filex,also look into child_process before using this code.

const {  readFileSync } = require('fs');
const {exec} = require("child_process");
function executeEachFile(command){
    exec(command, (error, stdout, stderr) => {
        if(error){
            console.log(error);
        }
        console.log("stdout: " + stdout)
      });
}


function readFile(path){
    const output = readFileSync(path,"utf8").split("\n").map(file=>{
        return file.replace("\r","");
    });
    console.log(output)
    return output
};



function IntervalLoop(ArrayofFiles){
    let counter = 0;
    const interval  = setInterval(()=>{
        const commandName = "node "+ ArrayofFiles[counter]; 
        console.log(commandName);
        executeEachFile(commandName);
        counter++;
        console.log(counter);
        if (ArrayofFiles.length  == counter){
            clearInterval(interval);
        }
    },300)
}

const fileNames = readFile("exec.txt");
IntervalLoop(fileNames);

Upvotes: 1

Related Questions