Notice: file_put_contents(): Write of 11296 bytes failed with errno=28 No space left on device in /var/www/tgoop/post.php on line 50

Warning: file_put_contents(): Only 8192 of 19488 bytes written, possibly out of free disk space in /var/www/tgoop/post.php on line 50
Node.JS [ru] | Серверный JavaScript@we_use_js P.4532
WE_USE_JS Telegram 4532
👩‍💻 Задачка по 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
👍7



tgoop.com/we_use_js/4532
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/4532

View MORE
Open in Telegram


Telegram News

Date: |

6How to manage your Telegram channel? During the meeting with TSE Minister Edson Fachin, Perekopsky also mentioned the TSE channel on the platform as one of the firm's key success stories. Launched as part of the company's commitments to tackle the spread of fake news in Brazil, the verified channel has attracted more than 184,000 members in less than a month. With the administration mulling over limiting access to doxxing groups, a prominent Telegram doxxing group apparently went on a "revenge spree." Ng, who had pleaded not guilty to all charges, had been detained for more than 20 months. His channel was said to have contained around 120 messages and photos that incited others to vandalise pro-government shops and commit criminal damage targeting police stations. The Channel name and bio must be no more than 255 characters long
from us


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