首页 > 解决方案 > 如何根据深度值创建文件夹和子文件夹

问题描述

查看在深度 0 处,创建一个名为 0 的文件夹,并在其中创建一个文件,其相对路径为内容。在深度 1:除了应该对深度 0 执行的操作之外,创建两个名为 0 和 1 的子文件夹,并创建一个文件以分别保存其路径。深度2:除了深度1应该做的事情外,在深度1创建的文件夹中创建子文件夹,命名为0、1、2,并按照相同的规则创建文件。在深度 N:相同的规则。

我试过了,但我认为这不是正确的答案?

const fs = require("fs");

const createPathForDepth = (depth) => {
  if (depth <= -1) return console.log("done");
  let tmp = depth;
  let relativePath;
  const path = `./tmp/${depth}`;

  try {
    if (!fs.existsSync(path)) {
      fs.mkdirSync(path);
      while (tmp > -1) {
        relativePath = `${path}/${tmp}`;
        fs.mkdirSync(relativePath);
        console.log("folder created", relativePath);
        fs.writeFileSync(
          `${relativePath}/${tmp}.txt`,
          `relativePath = ${relativePath}/${tmp}.txt`
        );
        console.log("file created", tmp, ".txt");
        tmp--;
      }
    }
  } catch (err) {
    console.error(err);
  }
  depth--;
  createPathForDepth(depth);
};

标签: node.jsdirectorytree

解决方案


推荐阅读