Javascript.RU

Создать новую тему Ответ
 
Опции темы Искать в теме
  #1 (permalink)  
Старый 16.12.2022, 10:42
Кандидат Javascript-наук
Отправить личное сообщение для mik888em Посмотреть профиль Найти все сообщения от mik888em
 
Регистрация: 21.06.2020
Сообщений: 142

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

Написал код, выполняю в nodejs, но получаю ошибку:
ReferenceError: getFolderSize is not defined


Код:
// Step 1
const fs = require('fs');
const path = require('path');
const spisok = [[SPISOK]];

let pytkpystoypapke; // variable to store the path to the found folder
let itog; // variable to store the path to the found folder in step 2

for (let i = 0; i < spisok.length; i++) {
  let folder = spisok[i];
  let folderSize = getFolderSize(folder); // function to get the size of a folder, not provided in the question
  if (folderSize < 1000000) {
    if (i < spisok.length - 1) {
      let nextFolder = spisok[i + 1];
      let nextFolderSize = getFolderSize(nextFolder);
      if (nextFolderSize > 1000000) {
        pytkpystoypapke = folder;
        break;
      }
    }
  }
}

if (pytkpystoypapke) {
  itog = pytkpystoypapke;
}

// Now, the variable itog should contain the path to the found folder whose size is less than 1000000 bytes and the next folder has a size greater than 1000000 bytes.
Ответить с цитированием
  #2 (permalink)  
Старый 16.12.2022, 11:43
Аватар для Aetae
Тлен
Отправить личное сообщение для Aetae Посмотреть профиль Найти все сообщения от Aetae
 
Регистрация: 02.01.2010
Сообщений: 6,492

Тут английским языком написано "function to get the size of a folder, not provided in the question".
Палишься.
__________________
29375, 35
Ответить с цитированием
  #3 (permalink)  
Старый 16.12.2022, 11:53
Кандидат Javascript-наук
Отправить личное сообщение для mik888em Посмотреть профиль Найти все сообщения от mik888em
 
Регистрация: 21.06.2020
Сообщений: 142

Пакет get-folder-size на 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"
}
} else {
pytkpystoypapke = spisok[i]; // save path to current folder in "pytkpystoypapke"
}
}
}

[[ITOG]] = pytkpystoypapke; // save path to found folder in "itog" variable

// Output result
console.log(itog);

Последний раз редактировалось mik888em, 16.12.2022 в 13:00.
Ответить с цитированием
  #4 (permalink)  
Старый 17.12.2022, 13:00
Кандидат Javascript-наук
Отправить личное сообщение для mik888em Посмотреть профиль Найти все сообщения от mik888em
 
Регистрация: 21.06.2020
Сообщений: 142

сам разобрался в, вот готовый код:
// 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;
Ответить с цитированием
Ответ



Опции темы Искать в теме
Искать в теме:

Расширенный поиск


Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Где ошибка в коде разрезки файла? mik888em Events/DOM/Window 0 19.01.2021 04:16
Помогите найти в чем ошибка Pashok Элементы интерфейса 6 26.02.2013 20:20
ie6-7 В какой строке ошибка, как найти эту строку? aRpi Internet Explorer 1 04.04.2012 19:06
не могу найти ошибку в коде MasterP Общие вопросы Javascript 1 03.07.2011 02:54
Отладка. При клике на элемент найти функцию-обработчик в коде romangaag Events/DOM/Window 3 24.10.2010 03:09