0

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?

2
  • What have you tried so far? I mean it's not that difficult. Use fs.readdir to read all the files from a directory and execute each of them using exec function from child_process module readdir exec Commented Dec 19, 2020 at 19:22
  • @Molda I had no idea how to approach this so I haven't been able to try anything yet (noobie alert). Not familiar with fs.readdir ; thanks for the hint. Going to read about it now! If you can share any line of codes that can guide me towards the solution would be awesome. Thanks Commented Dec 19, 2020 at 19:32

1 Answer 1

1

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);
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.