Найти пустую папку. Но находит последюю в списке.

Поддержка
  • Есть список [[SPISOK]] , каждый элемент списка- это путь к определённой папке.

    Нужно найти первую пустую (меньше 1 мб) папку и записать путь к ней в перем [[ITOG]] , но должно выполняться условие что после неё в списке [[SPISOK]]
    стоит папка размером 100мб или больше.

    Пробовал Nodejs 18 пакет get-folder-size и функция getFolderSize но не заработало.

    Использую Nodejs 18. Реализую определение размера папок с помощью встроенных инструментов fs.
    Но получаю в переменной itog просто самую последнюю папку в списке, она весит 41 мб. ..не подпадая под условия быть меньше 1 мб и после нее должна в списке стоять папка более 100 мб что также не выполняется т к после неё нет ни одного элемента в списке.

    Код:

    // Step 1
    const fs = require('fs');
    const path = require('path');
    
    const spisok = [[SPISOK]];
    
    
    // Declare variables
    let pytkpystoypapke = ""; // path to found folder with size less than 1000000 bytes
    let itog = ""; // path to found folder will be saved in this variable
    
    // Loop through all folders in list "spisok"
    for (let i = 0; i < spisok.length; i++) {
      let folderSize = fs.statSync(spisok[i]).size; // get size of current folder
      if (folderSize < 1000000) { // check if size is less than 1000000 bytes
        if (i < spisok.length - 1) { // check if there is another folder in list "spisok"
          let nextFolderSize = fs.statSync(spisok[i + 1]).size; // get size of next folder
          if (nextFolderSize > 1000000) { // check if next folder size is greater than 1000000 bytes
            pytkpystoypapke = spisok[i]; // save path to current folder in "pytkpystoypapke"
            break; // exit the loop
          }
        } else {
          pytkpystoypapke = spisok[i]; // save path to current folder in "pytkpystoypapke"
          break; // exit the loop
        }
      }
    }
    
    itog = pytkpystoypapke; // save path to found folder in "itog" variable
    [[ITOG]] = pytkpystoypapke; // save path to found folder in "itog" variable
    
    // Output result
    console.log(itog);
    
  • Сам разобрался, может кому-то будет полезно, вот готовый код, выполнять в кубике node.js (я выполнял в node18) .... кстати, больше 80% кода сгенерирована нейронкой https://chat.openai.com/chat

    Задача выполняется двумя кубиками node.js

    1) Сначала ищем из каталога все папки и переворачиваем этот список . Полученный список сохраняем в [[SPISOK]]

    // Step 1
    // Get the path to the "D:\\2 отправленое\\АНАЛИЗ" folder
    const path = "D:\\2 отправленое\\АНАЛИЗ";
    
    // Create an empty list to store the paths to the folders inside the "creep-analysis" folder
    let spisok = [];
    
    // Use the fs (file system) module to read the contents of the "creep-analysis" folder
    const fs = require('fs');
    const files = fs.readdirSync(path);
    
    // Loop through the contents of the "creep-analysis" folder and add the paths to the folders to the "spisok" list
    files.forEach((file) => {
      // Check if the current item is a folder
      if (fs.lstatSync(path + '/' + file).isDirectory()) {
        // Add the path to the folder to the "spisok" list
        spisok.push(path + '/' + file);
      }
    });
    
    // Step 2
    // Sort the "spisok" list in descending order by the number that each folder name starts with
    spisok.sort((a, b) => {
      // Get the folder name from the path of each item in the list
      const folderNameA = a.split('/').pop();
      const folderNameB = b.split('/').pop();
    
      // Extract the number that each folder name starts with
      const numberA = parseInt(folderNameA.match(/^\d+/)[0]);
      const numberB = parseInt(folderNameB.match(/^\d+/)[0]);
    
      // Compare the numbers and sort the list in descending order
      return numberB - numberA;
    });
    
    // Step 3
    // Save the sorted "spisok" list to the "itog" variable
    [[SPISOK]] = spisok;
    
    

    2) Далее ищем папку которая имеет вес меньше 1 мб и при условии что в каталоге где она лежит следующей будет папка с весом >=100мб
    Готовый рабочий код, полный путь к итоговой папке сохраняется в [[PYT_K_PROSHLOY_PYSTOY_PAPKE]]:

    // Declare the list "spisok"
    let spisok = [[SPISOK]];
    const fs = require('fs');
    
    
    // Use a for loop to go through all elements of the list "spisok"
    for (let i = 0; i < spisok.length; i++) {
    
        let folderPath = spisok[i]; // Assign each value of the loop to the variable "folderPath"
    
        //console.log(folderPath); // Print the value of "folderPath" in the log
    
    
    
        // шаг 1. начитаем получать размер папки путь к ней лежит в folderPath
        function getFolderSize(path) {
        let totalSize = 0;
        const files = fs.readdirSync(path);
        for (let i = 0; i < files.length; i++) {
        const stats = fs.statSync(path + '//' + files[i]);
        if (stats.isFile()) {
        totalSize += stats.size;
        }
        else if (stats.isDirectory()) {
        totalSize += getFolderSize(path + '//' + files[i]);
        }
        }
        return totalSize;
        }
        const folderSize = getFolderSize(folderPath);
        // закончили получать размер папки "folderPath" 
        // и размер записали в "folderSize"
    
    
    
    
        if (folderSize < 1000000); {
    
            // шаг 2. получаем размер папки лежащей ниже
                let nextElement = spisok[i + 1];
                function getFolderSize(path) {
                let totalSize = 0;
                const files = fs.readdirSync(path);
                for (let i = 0; i < files.length; i++) {
                const stats = fs.statSync(path + '//' + files[i]);
                if (stats.isFile()) {
                totalSize += stats.size;
                }
                else if (stats.isDirectory()) {
                totalSize += getFolderSize(path + '//' + files[i]);
                }
                }
                return totalSize;
                }
                const nextFolderSize = getFolderSize(nextElement);
      
            // закончили получать размер папки лежащей ниже и запись
            // записали размер в "nextFolderSize"
    
            if (nextFolderSize > 100000000) {
                 console.log(folderPath);
                 //console.log(folderSize);
                 //console.log(folderPath);
                 [[PYT_K_PROSHLOY_PYSTOY_PAPKE]] = folderPath;
                 break
    }
    }
    }