G
G
gleendo2017-07-29 06:43:37
Node.js
gleendo, 2017-07-29 06:43:37

Why is the list of files in a directory and subdirectories not displayed as expected?

Why, when processing files synchronously, before the output of the music subdirectory, several more files are output, although they are not ordered in the explorer? According to the idea, the music subdirectory should go first, the output of its files, and then the output of all other files to a higher level.

let fs = require("fs");
let base = "C://users/iamevg_/desktop/music";

const readDir = (base, lvl) => {
  let files = fs.readdirSync(base);

  files.forEach(file => {
    let state = fs.statSync(`${base}/${file}`);

    if (state.isDirectory()) {
      console.log("\n" + " ".repeat(lvl * 2) + file + "\n");

      let localBase = `${base}/${file}`;

      readDir(localBase, lvl + 1);
    } else {
      console.log(" ".repeat(lvl * 2) + file);
    }
  });
};

readDir(base, 0);

2200866a4c0f49a59fec2a94d3bfbea9.png4f3ca18556c04aa29d1191eb35d64b6f.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
dummyman, 2017-07-29
@dummyman

The answer is logical. Since you do not set the order in which you need the folders - get a mess.
Although in reality, the content will be sorted in the order they were created on the local hard drive.

let files = fs.readdirSync(base).reverse();   // Получаешь отсортированный 
                                               // список по имени в обратном порядке

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question