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

Создайте приложение на Node.js, которое принимает путь к текстовому файлу в качестве аргумента командной строки, подсчитывает количество строк, слов и символов в файле, а затем сохраняет результат в stats.json. Программа также должна уметь выводить статистику в консоль.

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

➡️ Пример:

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

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

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

const action = process.argv[2];
const filePath = process.argv[3];
const reportFile = 'stats.json';

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

async function analyzeFile(file) {
const content = await readFile(file, 'utf8');
const lines = content.split('\n').length;
const words = content.split(/\s+/).filter(Boolean).length;
const chars = content.length;

return { lines, words, chars };
}

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

async function printReport(file) {
const stats = await analyzeFile(file);
console.log(`Файл: ${file}`);
console.log(`Количество строк: ${stats.lines}`);
console.log(`Количество слов: ${stats.words}`);
console.log(`Количество символов: ${stats.chars}`);
}

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



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

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

Создайте приложение на Node.js, которое принимает путь к текстовому файлу в качестве аргумента командной строки, подсчитывает количество строк, слов и символов в файле, а затем сохраняет результат в stats.json. Программа также должна уметь выводить статистику в консоль.

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

➡️ Пример:

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

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

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

const action = process.argv[2];
const filePath = process.argv[3];
const reportFile = 'stats.json';

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

async function analyzeFile(file) {
const content = await readFile(file, 'utf8');
const lines = content.split('\n').length;
const words = content.split(/\s+/).filter(Boolean).length;
const chars = content.length;

return { lines, words, chars };
}

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

async function printReport(file) {
const stats = await analyzeFile(file);
console.log(`Файл: ${file}`);
console.log(`Количество строк: ${stats.lines}`);
console.log(`Количество слов: ${stats.words}`);
console.log(`Количество символов: ${stats.chars}`);
}

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

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


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

View MORE
Open in Telegram


Telegram News

Date: |

To edit your name or bio, click the Menu icon and select “Manage Channel.” There have been several contributions to the group with members posting voice notes of screaming, yelling, groaning, and wailing in different rhythms and pitches. Calling out the “degenerate” community or the crypto obsessives that engage in high-risk trading, Co-founder of NFT renting protocol Rentable World emiliano.eth shared this group on his Twitter. He wrote: “hey degen, are you stressed? Just let it out all out. Voice only tg channel for screaming”. Users are more open to new information on workdays rather than weekends. Public channels are public to the internet, regardless of whether or not they are subscribed. A public channel is displayed in search results and has a short address (link). In handing down the sentence yesterday, deputy judge Peter Hui Shiu-keung of the district court said that even if Ng did not post the messages, he cannot shirk responsibility as the owner and administrator of such a big group for allowing these messages that incite illegal behaviors to exist.
from us


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