Как генерировать и сохранить структуру папки в формате YAML/JSON/TXT с помощью node.js? [закрыто]Javascript

Форум по Javascript
Ответить
Anonymous
 Как генерировать и сохранить структуру папки в формате YAML/JSON/TXT с помощью node.js? [закрыто]

Сообщение Anonymous »

Оператор задачи < /h3>
мне нужен скрипт node.js, который:

✅ рекурсивно сканирует каталог и перечисляет все файлы и папки.

✅ исключает ненужные каталоги, такие как Node_modules < /code>, .git < /code>, delt < /код>, и т. Д. В разных форматах (TXT, JSON и YAML).

✅ использует отдельные сценарии для каждого формата вместо одного сценария. Есть лучшие практики для обработки больших структур каталогов в node.js?

📌 Должен ли я добавить параметры CLI, чтобы облегчить выбор формата? />
  • Сохранить структуру папки как txt (

    Код: Выделить всё

    generate_txt.js)
    [/list]
    import { readdirSync, statSync, writeFileSync } from "fs";
    import { join } from "path";
    
    const EXCLUDED_DIRS = new Set(["node_modules", ".git", "dist", "build", "out"]);
    
    /**
    * Recursively retrieves folder structure and formats it as a TXT hierarchy.
    */
    function getFolderStructure(dir, prefix = "") {
    let structure = "";
    const items = readdirSync(dir).filter(
    (item) => !EXCLUDED_DIRS.has(item) && !item.startsWith(".")
    );
    
    items.forEach((item, index) => {
    const fullPath = join(dir, item);
    const isDir = statSync(fullPath).isDirectory();
    const isLast = index === items.length - 1;
    
    structure += `${prefix}${isLast ? "└── " : "├── "}${item}${
    isDir ? "\\" : ""
    }\n`;
    
    if (isDir) {
    structure += getFolderStructure(
    fullPath,
    prefix + (isLast ? "    " : "│   ")
    );
    }
    });
    
    return structure;
    }
    
    // Get directory to scan
    const rootDir = process.argv[2] || process.cwd();
    const outputFile = process.argv[3] || "folder_structure.txt";
    
    // Generate structure and save
    const folderStructure = getFolderStructure(rootDir);
    writeFileSync(outputFile, folderStructure, "utf8");
    console.log(`Folder structure saved to ${outputFile}`);
    
    < /code>
    
    [list]
    [*] Сохранить структуру папки как json (generate_json.js)
    [/list]
    import { readdirSync, statSync, writeFileSync } from "fs";
    import { join } from "path";
    
    const EXCLUDED_DIRS = new Set(["node_modules", ".git", "dist", "build", "out"]);
    
    /**
    * Recursively retrieves folder structure as a JSON object.
    */
    function getFolderStructure(dir) {
    let structure = {};
    const items = readdirSync(dir).filter(
    (item) => !EXCLUDED_DIRS.has(item) && !item.startsWith(".")
    );
    
    items.forEach((item) => {
    const fullPath = join(dir, item);
    const isDir = statSync(fullPath).isDirectory();
    structure[item] = isDir ? getFolderStructure(fullPath) : null;
    });
    
    return structure;
    }
    
    // Get directory to scan
    const rootDir = process.argv[2] || process.cwd();
    const outputFile = process.argv[3] || "folder_structure.json";
    
    // Generate structure and save
    const folderStructure = getFolderStructure(rootDir);
    writeFileSync(outputFile, JSON.stringify(folderStructure, null, 2), "utf8");
    console.log(`Folder structure saved to ${outputFile}`);
    < /code>
    
    [list]
    [*] Сохранить структуру папки как yaml (generate_yaml.js)
    [/list]
    import { readdirSync, statSync, writeFileSync } from "fs";
    import { join } from "path";
    
    const EXCLUDED_DIRS = new Set(["node_modules", ".git", "dist", "build", "out"]);
    
    /**
    * Recursively retrieves folder structure and converts it to YAML format.
    */
    function getFolderStructure(dir, depth = 0) {
    let structure = "";
    const items = readdirSync(dir).filter(
    (item) => !EXCLUDED_DIRS.has(item) && !item.startsWith(".")
    );
    
    items.forEach((item) => {
    const fullPath = join(dir, item);
    const isDir = statSync(fullPath).isDirectory();
    
    structure += `${"  ".repeat(depth)}${item}: ${isDir ? ""  : "null"}\n`;
    
    if (isDir) {
    structure += getFolderStructure(fullPath, depth + 1);
    }
    });
    
    return structure;
    }
    
    // Get directory to scan
    const rootDir = process.argv[2] || process.cwd();
    const outputFile = process.argv[3] || "folder_structure.yaml";
    
    // Generate structure and save
    const folderStructure = getFolderStructure(rootDir);
    writeFileSync(outputFile, folderStructure, "utf8");
    console.log(`Folder structure saved to ${outputFile}`);
    < /code>
    
    Как использовать эти сценарии?generate_txt.js
  • Код: Выделить всё

    generate_json.js
  • generate_yaml.js


    Запустите их с помощью терминала:
    node generate_txt.js /path/to/directory output.txt
    node generate_json.js /path/to/directory output.json
    node generate_yaml.js /path/to/directory output.yaml
    < /code>

    Если не указан каталог, он по умолчанию в текущий рабочий каталог. < /li>
    Если выходной файл не указан, он по умолчанию по умолчанию. /> Пример выходов < /p>
    txt output (folder_structure.txt)
    app\
    about\
    page.tsx
    admin\
    customers\
    page.tsx
    < /code>
    json output (folder_structure.json)
    {
    "app": {
    "about": {
    "page.tsx": null
    },
    "admin": {
    "customers": {
    "page.tsx": null
    }
    }
    }
    }
    < /code>
    yaml output (folder_structure.yaml)
    app:
    about:
    page.tsx: null
    admin:
    customers:
    page.tsx: null


    Подробнее здесь: https://stackoverflow.com/questions/795 ... ing-node-j
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Javascript»