Opening multiple processes in Node.JS

There was a question, I have the code on Node.JS and I want to open several similar files at the same time (by loop), when I try to do this via execFile / spawn, the script runs, but nothing happens. When you open a loop, a single file through execFile / spawn, everything happens fine, when opening several files through a double-click in the explorer, it is also normal.

I attach the code:

const spawn = require('child_process').spawn;
const fs = require('fs');

var files = fs.readdirSync('D:\\Downloads\\runBots\\');
var countFiles = 0;
var BotsProcess = new Array(10);

var startApplication = function(){
    for (var i in files) countFiles++;
    console.log("Bots in directory: " + countFiles);
    for(var j in countFiles) {
        BotsProcess[i] = spawn('D:\\Downloads\\runBots\\' + files[j], {shell : true});
    }
}
startApplication();

Upvotes: 0

Views: 237

Answers (1)

Viktor W
Viktor W

Reputation: 1149

The problem is the for loop. The variable countFiles is a number, not an iterable. You probably want

for (var j in files) {
    ...
}

Also, I cannot help but point out:

To get countFiles, you can simply use files.length.

You could also use a for of loop instead which will assign the value to j instead of the index, like this:

for(var j of files) {
    BotsProcess[i] = spawn('D:\\Downloads\\runBots\\' + j, {shell : true});
}

Upvotes: 1

Related Questions