这还是人类能理解的吗

问题描述 投票:0回答:1

你知道我学习了编程基础知识,我有 4 年的经验,这段代码对我来说没有任何意义,任何人都可以向我解释一下,就像 5 岁的孩子一样,这段代码的作用是我试图遍历嵌套文件夹

c:\用户\欢迎\桌面\Dlang est1 est2 est3 est4

const fs = require("fs");
const path = require("path");

let dir = __dirname;

let iterate = function(dir) {
  const stack = [dir];

  while (stack.length > 0) {
    let currentDir = stack.pop();

    fs.readdirSync(currentDir).forEach((item) => {
      let fullPath = path.join(currentDir, item);

      if (fs.statSync(fullPath).isDirectory()) {
        console.log(fullPath); // Output the directory path
        stack.push(fullPath);   // Push subdirectories onto the stack
      } else {
        console.log(fullPath); // Output the file path
      }
    });
  }
};

iterate(dir);
 

// expected test1/test2/test3/tes4
javascript node.js file directory
1个回答
0
投票

此代码将通过在当前目录上执行 for 循环来遍历目录。如果它是一个文件,那么我们找到了一个。如果它是一个目录,我们应该稍后遍历它。与此同时,我们将通过将其推送到要扫描的目录队列来安排它。

也许,也许不会,递归可以进一步证明这个想法。

const fs = require("fs");
const path = require("path");

let dir = __dirname;

let iterate = function(currentDir) {

  fs.readdirSync(currentDir).forEach((item) => {
    let fullPath = path.join(currentDir, item);

    if (fs.statSync(fullPath).isDirectory()) {
      console.log(fullPath); // Output the directory path
      iterate(fullPath)
    } else {
      console.log(fullPath); // Output the file path
    }
  });

};

iterate(dir);

这两个代码都没有经过我的测试,但它们看起来可能可以用于遍历目录及其子目录的所有条目。

© www.soinside.com 2019 - 2024. All rights reserved.