ms_nitrogen ms_nitrogen - 2 months ago 12
Javascript Question

Infinite loop instead of moving onto next folder

I am trying to make a library function where using a JSON file (created by directory tree), where it digs into each folder, to then build up an interactive

<ul>
list. I'm testing it out via console, where it loops infinitely in folder
json
(as per this example).

My json file

My code is as follows ...

var directory = './app';
var jSon = dirTree(directory, ['.js', '.json', '.html']);

console.log(jSon.children.length)

libBuilder(directory, jSon.children)

function libBuilder(directory, array) {
for (i=0; i < array.length; i++) {
if (fs.statSync(path.join(directory, array[i].name)).isFile()) {
console.log(colors.cyan(array[i].name))
} else if ( fs.statSync(path.join(directory, array[i].name)).isDirectory()) {
console.log(colors.red(array[i].name));
libBuilder(path.join(directory, array[i].name), array[i].children)
}
};
}


This console output repeats indefinitely:

json
comic.json
config.json
library.json
dragscroll.js
file.js


How do I fix up the code to where it reads everything in a folder than then moves out to check the next time in the object array?

Answer
for (i=0; i < array.length; i++) { <-- i is global!

You need to define i with var so it is not global. Each time you call it, it gets reset to zero on each iteration.

for (var i=0; i < array.length; i++) {