WE_USE_JS Telegram 4907
👩‍💻 Задачка по NodeJS

Создайте приложение на Node.js, которое принимает путь к папке в качестве аргумента командной строки и создает файл report.json, содержащий статистику по этой папке: количество файлов, количество папок, и общий размер всех файлов.

Программа должна уметь выводить статистику по папке в консоль и сохранять её в файл.

➡️ Пример:

node app.js report /path/to/folder — создает файл report.json с данными о содержимом папки.
node app.js print /path/to/folder — выводит статистику о папке в консоль.

Решение задачи ⬇️

const fs = require('fs');
const path = require('path');
const { promisify } = require('util');
const readdir = promisify(fs.readdir);
const stat = promisify(fs.stat);

const action = process.argv[2];
const folderPath = process.argv[3];
const reportFile = 'report.json';

if (!action || !folderPath) {
console.log('Используйте: node app.js <report|print> <путь к папке>');
process.exit(1);
}

async function analyzeFolder(folder) {
const entries = await readdir(folder, { withFileTypes: true });
let totalSize = 0;
let fileCount = 0;
let folderCount = 0;

for (const entry of entries) {
const fullPath = path.join(folder,
entry.name);
if (entry.isDirectory()) {
folderCount++;
const { totalSize: folderSize, fileCount: folderFiles, folderCount: subFolderCount } = await analyzeFolder(fullPath);
totalSize += folderSize;
fileCount += folderFiles;
folderCount += subFolderCount;
} else if (entry.isFile()) {
const fileStats = await stat(fullPath);
fileCount++;
totalSize += fileStats.size;
}
}

return { totalSize, fileCount, folderCount };
}

async function generateReport(folder) {
const stats = await analyzeFolder(folder);
const reportData = {
folder: folder,
files: stats.fileCount,
folders: stats.folderCount,
totalSize: stats.totalSize,
};

fs.writeFile(reportFile, JSON.stringify(reportData, null, 2), (err) => {
if (err) {
console.error('Ошибка при записи отчета:', err);
process.exit(1);
}
console.log(`Отчет сохранен в ${reportFile}`);
});
}

async function printReport(folder) {
const stats = await analyzeFolder(folder);
console.log(`Папка: ${folder}`);
console.log(`Количество файлов: ${stats.fileCount}`);
console.log(`Количество папок: ${stats.folderCount}`);
console.log(`Общий размер файлов: ${stats.totalSize} байт`);
}

if (action === 'report') {
generateReport(folderPath);
} else if (action === 'print') {
printReport(folderPath);
} else {
console.log('Неизвестное действие. Используйте "report" или "print".');
}
Please open Telegram to view this post
VIEW IN TELEGRAM



tgoop.com/we_use_js/4907
Create:
Last Update:

👩‍💻 Задачка по NodeJS

Создайте приложение на Node.js, которое принимает путь к папке в качестве аргумента командной строки и создает файл report.json, содержащий статистику по этой папке: количество файлов, количество папок, и общий размер всех файлов.

Программа должна уметь выводить статистику по папке в консоль и сохранять её в файл.

➡️ Пример:

node app.js report /path/to/folder — создает файл report.json с данными о содержимом папки.
node app.js print /path/to/folder — выводит статистику о папке в консоль.

Решение задачи ⬇️

const fs = require('fs');
const path = require('path');
const { promisify } = require('util');
const readdir = promisify(fs.readdir);
const stat = promisify(fs.stat);

const action = process.argv[2];
const folderPath = process.argv[3];
const reportFile = 'report.json';

if (!action || !folderPath) {
console.log('Используйте: node app.js <report|print> <путь к папке>');
process.exit(1);
}

async function analyzeFolder(folder) {
const entries = await readdir(folder, { withFileTypes: true });
let totalSize = 0;
let fileCount = 0;
let folderCount = 0;

for (const entry of entries) {
const fullPath = path.join(folder,
entry.name);
if (entry.isDirectory()) {
folderCount++;
const { totalSize: folderSize, fileCount: folderFiles, folderCount: subFolderCount } = await analyzeFolder(fullPath);
totalSize += folderSize;
fileCount += folderFiles;
folderCount += subFolderCount;
} else if (entry.isFile()) {
const fileStats = await stat(fullPath);
fileCount++;
totalSize += fileStats.size;
}
}

return { totalSize, fileCount, folderCount };
}

async function generateReport(folder) {
const stats = await analyzeFolder(folder);
const reportData = {
folder: folder,
files: stats.fileCount,
folders: stats.folderCount,
totalSize: stats.totalSize,
};

fs.writeFile(reportFile, JSON.stringify(reportData, null, 2), (err) => {
if (err) {
console.error('Ошибка при записи отчета:', err);
process.exit(1);
}
console.log(`Отчет сохранен в ${reportFile}`);
});
}

async function printReport(folder) {
const stats = await analyzeFolder(folder);
console.log(`Папка: ${folder}`);
console.log(`Количество файлов: ${stats.fileCount}`);
console.log(`Количество папок: ${stats.folderCount}`);
console.log(`Общий размер файлов: ${stats.totalSize} байт`);
}

if (action === 'report') {
generateReport(folderPath);
} else if (action === 'print') {
printReport(folderPath);
} else {
console.log('Неизвестное действие. Используйте "report" или "print".');
}

BY Node.JS [ru] | Серверный JavaScript


Share with your friend now:
tgoop.com/we_use_js/4907

View MORE
Open in Telegram


Telegram News

Date: |

Your posting frequency depends on the topic of your channel. If you have a news channel, it’s OK to publish new content every day (or even every hour). For other industries, stick with 2-3 large posts a week. How to create a business channel on Telegram? (Tutorial) With Bitcoin down 30% in the past week, some crypto traders have taken to Telegram to “voice” their feelings. Over 33,000 people sent out over 1,000 doxxing messages in the group. Although the administrators tried to delete all of the messages, the posting speed was far too much for them to keep up. “[The defendant] could not shift his criminal liability,” Hui said.
from us


Telegram Node.JS [ru] | Серверный JavaScript
FROM American